Add CSS to a div using a function in knockoutJS - javascript

I am trying to implement CSS binding in knockoutJS.
I want to print all the names in the names array, One after another.
The catch is that there is another array which has some special names.
All the special names should get "good" CSS class. And the rest, "bad" css class.
Here is something that i have tried:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div data-bind="foreach : items">
<div data-bind="text: $data, css: checkName($data)" ></div>
</div>
</body>
</html>
JAVASCRIPT
var dataModel = function(){
self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
self.names = ["ron","harry"];
self.checkName = ko.observable(function(name){
if( $.inArray(name,self.names) ){
return "good";
}
else{
return "bad";
}
});
};
ko.applyBindings(new dataModel());
FIDDLE - http://jsbin.com/difaluwo/2/edit
Now its not woking. In console its giving me "Script error. (line 0)"
Thanks !

The out of the box CSS binding is a little tricky. You specify class name and then the condition when it will be applied.
JSBIN
<div data-bind="foreach : items">
<div data-bind="text: $data, css: { good: isGoodName($data), bad: !isGoodName($data) }" ></div>
</div>
And your view model:
var dataModel = function(){
self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
self.names = ["ron","harry"];
self.isGoodName = function (name) {
return $.inArray(name, self.names) !== -1;
};
};
ko.applyBindings(new dataModel());

Related

Substring helper in handlebars

Can i write a helper in Handlebars that can tell if a string is a substring of another string?
I wrote the following code, but it doesn't seem to be working
This is the helper:
'if_sub': function(a, b, opts) {
if (a.includes(b))
return opts.fn(this);
else
return opts.inverse(this);
}
And this is the implementation:
{{#if_sub colvalues "success"}}
<td class="log-success"> {{colvalues}} </td>
{{/if_sub}}
just little mistake . if (a.includes(b)) should be if (b.includes(a))
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>How to render html with Handlebars.js</title>
<script src="https://cdn.jsdelivr.net/handlebarsjs/4.0.3/handlebars.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script id="simple-template" type="text/x-handlebars-template">
{{#if_sub colvalues "success"}}
<td class="log-success"> {{colvalues}} </td>
{{/if_sub}}
</script>
<script type="text/javascript">
Handlebars.registerHelper("if_sub",function(a, b, opts) {
if (b.includes(a)){
return opts.fn(this);
}
else{
return opts.inverse(this);
}
});
//wait for page to load
$(document).ready(function(){
var raw_template = $('#simple-template').html();
var template = Handlebars.compile(raw_template);
var data = {colvalues:"suc"}; //change value and see.
var html = template(data);
$('#main').append(html);
});
</script>
</head>
<body>
<!-- Insertion point for handlebars template -->
<div id="main" style="margin-left:100px">
</div>
</body>
</html>

How to get the autocomplete in angular js?

I have a object which contains name and id.I just want to do the autocomplete based on name.I have tried the code as shown below
//Js file
var app=angular.module("myapp",[]);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
$scope.complete=function(){
$("#autocomp").autocomplete({
source: $scope.persons.Id
});
};
}]);
//Html file
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta charset="UTF-8">
<title>Auto Complete based on name</title>
<script src="angularfiles/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="Jsfiles/autocomp.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p.Name}}
</div>
<div class="ui-widget">
<input type="text" id="autocomp" ng-keyup="complete()">
</div>
</body>
</html>
The above code may have some errors .Its not getting output which i want to have .Can anyone help me out to solve this problem.
Try like this,
HTML:
<div ng-app = "myapp">
<div ng-controller="controller">
<div class="ui-widget">
<input type="text" id="autocomp" auto-complete>
</div>
</div>
</div>
Js:
var app = angular.module("myapp",[]);
app.controller("controller",function($scope){
$scope.availableTags = [
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
}).directive("autoComplete",function(){
return function(scope,element,attrs){
var names =$.map(scope.availableTags,function(value){ return value.Name;
});
element.autocomplete({
source: names
});
};
});
Working jsbin
This is how you should use any jQuery API's in an AngularJS project (i believe). Anytime you are doing DOM Manipulation or jQuery things, it should be placed inside the link: function() {} via directive.
Probably the main problem with your code was that the source: $scope.persons.Id is just a number. The source needs to be an array of Strings (at least as per the documentation). So I seperated all the names from your persons array and placed them in a new array peopleNames
<!doctype html>
<html lang="en" ng-app="myapp">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="vendors/angular.min.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p.Name}}
</div>
<div class="ui-widget">
<input type="text" id="tags" autocomplete-directive>
</div>
<script>
var app = angular.module("myapp",[]);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
// array of only strings autocomplete
$scope.peopleNames = [];
for(var i = 0, j = $scope.persons.length; i < j; i++) {
$scope.peopleNames.push($scope.persons[i].Name);
}
}]);
app.directive('autocompleteDirective', [function($scope) {
return {
link: function(scope, element, attrs) {
element.autocomplete({
source: scope.peopleNames
});
}
};
}]);
</script>
</body>
</html>
Thank For every one for suggesting me answer.I have also done in another way .It may help to others.
//html file
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>Auto Complete based on name</title>
<script src="angularfiles/angular.js"></script>
<script src="angularfiles/angular-animate.js"></script>
<script src="angularfiles/ui-bootstrap-tpls-0.13.4.js"></script>
<script src="angularfiles/bootstrap-theme.css"></script>
<script src="Jsfiles/autocomp.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p}}</div>
<div class="ui-widget">
<input type="text" ng-model="selected" typeahead="p.Name for p in persons | filter:$viewValue">
</div>
</body>
</html>
//js file
var app = angular.module("myapp",['ui.bootstrap']);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
}]);

unable to bind image to img tag

I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,
JavaScript code:
WinJS.xhr({ url: urlToBeUsed }).then(
function (sportsResponse) {
var sportsJSON = JSON.parse(sportsResponse.responseText);
var listItems = sportsJSON.Videos.Data;
for (var i = 0; i < listItems.length; i++) {
var imageList = listItems[i].Items;
var count = imageList.length;
if (count > 0) {
listItems[i].Items[0].Images.forEach(imageIteration);
function imageIteration(value, index, array) {
var picture = value.Url;
var name = value.title;
sportsImageList.push({
title: name,
picture: picture
});
}
}
}
imageList.itemDataSource = sportsImageList.dataSource;
})
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- WinJS references -->
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<script src="/js/navigator.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/home/home.css" rel="stylesheet" />
<script src="/pages/sports/sports.js"></script>
</head>
<body>
<!-- The content that will be loaded and displayed. -->
<div class="fragment homepage" style="width:100%;height:100%;padding:10px">
<div class="myTemplate" data-win-control="WinJS.Binding.Template">
<div class="myItem">
<img data-win-bind="src:picture" style="width:100px;height:100px" />
</div>
</div>
<div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
</div>
</body>
</html>
I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images.
Where am I wrong?
All help and suggestions appreciated.
Thank you!
I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.
Change it to this:
imageList.winControl.itemDataSource = sportsImageList.dataSource;

HTML/JS: appendTo doesnt work

I wanted to dynamically append a Table/List to HTML page. My code as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lead Manager</title>
<link rel="stylesheet" href="themes/Bootstrap.css">
<link rel="stylesheet" href="themes/jquery.mobile.structure-1.2.0.min.css" />
<script src="themes/jquery-1.8.2.min.js"></script>
<script src="themes/jquery.mobile-1.2.0.min.js"></script>
</head>
<body id="body" name="body">
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Lead Manager</h1>
</div>
<div data-role="content" data-theme="a">
<h2>List of Leads</h2>
</div>
</div>
</body>
<script>
$(document).ready(function(e) {
//var data = Android.getLeads();
var data = [{"status":"1","name":"1","campaign":"1","date":"1"},{"status":"2","name":"2","campaign":"2","date":"2"}];
var items = [];
var date;
var name;
var status;
//eval(" var x = " + data + " ; ");
//var y = JSON.stringify(x);
$.each(data, function(key,val){
items.push('<tr><td>' + val.date + '</tr></td>');
});
var text = $('<table/>', { html: items.join('')});
$('<table/>', {
html: items.join('')
}).appendTo('body');
});
</script>
</html>
The Items[] variable is getting filled with the tr and td values. However, the appendTo, doesnt work. The JSON as you can see doesnt require eval as its already in the format required.
Please can you help?
The issue was mainly because of the jquery.mobile script as it wasnt allowing dynamic addition of html code.

Bootstrap Typeahead.js

I have been trying to get the bootstrap typeahead to work, with no luck whatsoever. I have pasted the code I have. I have reference Jquery-1.9.1 and typeahead.js. What am I doing wrong? Your help is much appreciated! Thanks.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<script src="Scripts/typeahead.js-master/test/vendor/jquery-1.9.1.js"></script>
<script src="Scripts/typeahead.js-master/src/typeahead.js"></script>
<title></title>
</head>
<body>
<form>
<div>
<input type="text" data-provide="typeahead" autocomplete="off" data-source='["arizona","alaska"]' />
</div>
</form>
</body>
</html>
It looks like you're getting confused between typeahead.js (by Twitter) and Twitter Bootstrap's Typeahead feature
You're including the library for typeahead.js
<script src="Scripts/typeahead.js-master/src/typeahead.js"></script>
but trying to use it like Twitter Bootstrap's typeahead feature.
Make sure you're including the Twitter Bootstrap library, if you want to use your current code:
<script type="text/javascript"
src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js">
</script>
Here's an example: jsFiddle
I hope this is what you expection. Here is the complete code try with necessary dependencies.
<!DOCTYPE html>
<html>
<head>
<title>Member</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="well">
<input type="text" class="span3" id="search" data-provide="typeahead" data-items="4" />
</div>
<script>
var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];
$('#search').typeahead({source: subjects})
</script>
</body>
</html>
The Type head File with add two features:
Type Space Bar Show All Auto Complete Data's
If you Give Data with Space also Can be Sort and Display Data's
Change The Lookup Function This:
lookup: function (event) {
var that = this,
items;
if (that.ajax) {
that.ajaxer();
}
else if (($.trim(that.$element.val())) == "") {
that.query = that.$element.val();
if (!that.query) {
return that.shown ? that.hide() : that;
}
items = that.source;
if (!items || !items.length) {
return that.shown ? that.hide() : that;
}
return that.render(items.slice(0, that.options.items)).show();
}
else {
that.query = $.trim(that.$element.val());
if (!that.query) {
return that.shown ? that.hide() : that;
}
items = that.grepper(that.source);
if (!items || !items.length) {
return that.shown ? that.hide() : that;
}
return that.render(items.slice(0, that.options.items)).show();
}
},

Categories

Resources