update the boolean value in md-select using angular material - javascript

am struggled in md-select model update when user changes the value need to update the flag as true.Actually i have to iterate the length of the model in md-select and in md-options i show like 1,2...5. if user changes the value in drop down means respective flag set to true other should be in false.kindly help me out this problem. following is my code and kindly tell me where i did the logical mistake:
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
</style>
<script language = "javascript">
angular
.module('testApp', ['ngMaterial'])
.controller('myCTRL', myCTRL);
function myCTRL ($scope) {
$scope.chooseValue =false;
$scope.selectedValue = 1;
$scope.testValue = [
{ isEnabled: false},
{ isEnabled: false },
{ isEnabled: false }
];
$scope.submitvalue = function(){
console.info($scope.testValue)
$scope.testValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalvalue)
}
}
</script>
</head>
<body ng-app = "testApp">
<div id = "inputContainer" class = "inputDemo"
ng-controller = "myCTRL as ctrl" ng-cloak>
<form role="form" name="deviceForm">
<div>
<md-input-container >
<label>select flags want to enable</label>
<md-select ng-model="selectedValue" >
<md-option ng-repeat="(key,value) in testValue">{{key}}</md-option>
</md-select>
</md-input-container>
</div>
</form>
<input type="submit" ng-click="submitvalue()">
</div>
</body>
</html>
Thanks in advance.

You can simply create a new copy of testValue object into finalValue variable, then do the boolean assignments in that and use. Please refer the below code.
console.info($scope.testValue)
$scope.finalValue = angular.copy($scope.testValue);
$scope.finalValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalValue)
We create a new copy of testValue using method angular.copy() and assign it to final value. Then we use your logic to assign the respective indexed boolean to true.
The problem with your original code, is that you are showing finalValue, without it being even defined as a variable and also no data manipulations were done to it!
Please refer the below working snippet, and let me know if you face any issues implementing the below code!
angular
.module('testApp', ['ngMaterial'])
.controller('myCTRL', myCTRL);
function myCTRL($scope) {
$scope.chooseValue = false;
$scope.finalValue = {};
$scope.selectedValue = 1;
$scope.testValue = [{
isEnabled: false
},
{
isEnabled: false
},
{
isEnabled: false
}
];
$scope.submitvalue = function() {
console.info($scope.testValue)
$scope.finalValue = angular.copy($scope.testValue);
$scope.finalValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalValue)
}
}
<html lang="en">
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
</style>
</head>
<body ng-app="testApp">
<div id="inputContainer" class="inputDemo" ng-controller="myCTRL as ctrl" ng-cloak>
<form role="form" name="deviceForm">
<div>
<md-input-container>
<label>select flags want to enable</label>
<md-select ng-model="selectedValue">
<md-option ng-repeat="(key,value) in testValue">{{key}}</md-option>
</md-select>
</md-input-container>
</div>
</form>
<input type="submit" ng-click="submitvalue()">
</div>
</body>
</html>

Related

angular material md-select ng-model set to undefined rules

When I execute this script, aForm.aField.$error contains {"required":true} BUT $scope.fruit is not set to undefined even though it is not in the md-option values. So the "required" validation is done but not the set to undefined.
<!doctype html>
<html ng-app="anApp">
<head>
<link rel="stylesheet" href="bower_components/angular-material/angular-material.min.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-messages/angular-messages.min.js"></script>
<script src="bower_components/angular-material/angular-material.js"></script>
<script src="bower_components/angular-animate/angular-animate.min.js"></script>
<script src="bower_components/angular-aria/angular-aria.min.js"></script>
<script>
angular.module('anApp', ['ngMessages', 'ngMaterial'])
.controller('aController', function ($scope, $timeout) {
$scope.fruitBasket = [{name:"apple", id:1}];
$scope.fruit = 100;
$scope.required = true;
});
</script>
</head>
<body ng-controller="aController">
{{aForm.aField.$error}}<br> [{{fruit}}]
<br>
<form name="aForm">
<md-input-container>
<label>Fruit</label>
<md-select name="aField" ng-required="required" ng-model="fruit">
<md-option ng-repeat="unFruit in fruitBasket" ng-value="unFruit.id"> {{unFruit.name}} </md-option>
</md-select>
<div ng-messages="aForm.aField.$error">
<div ng-message="required">Fruit required</div>
</div>
</md-input-container>
</form>
</body>
</html>
But when I execute this script, $scope.fruit is set to undefined after the timeout is executed:
<!doctype html>
<html ng-app="anApp">
<head>
<link rel="stylesheet" href="bower_components/angular-material/angular-material.min.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-messages/angular-messages.min.js"></script>
<script src="bower_components/angular-material/angular-material.js"></script>
<script src="bower_components/angular-animate/angular-animate.min.js"></script>
<script src="bower_components/angular-aria/angular-aria.min.js"></script>
<script>
angular.module('anApp', ['ngMessages', 'ngMaterial'])
.controller('aController', function ($scope, $timeout) {
$scope.fruitBasket = [{name:"apple", id:1}];
$scope.fruit = 100;
$scope.required = false;
$timeout(function() {
$scope.required = true;
}, 1000);
});
</script>
</head>
<body ng-controller="aController">
{{aForm.aField.$error}}<br> [{{fruit}}]
<br>
<form name="aForm">
<md-input-container>
<label>Fruit</label>
<md-select name="aField" ng-required="required" ng-model="fruit">
<md-option ng-repeat="unFruit in fruitBasket" ng-value="unFruit.id"> {{unFruit.name}} </md-option>
</md-select>
<div ng-messages="aForm.aField.$error">
<div ng-message="required">Fruit required</div>
</div>
</md-input-container>
</form>
</body>
</html>
When I look at angular's code, when invoking $$runValidators, there's this "prevValid" condition that seems to influence the "set to undefine" mecanism.
So it seems md-select (because of angular) is not always setting the model to undefined when it is not a valid value.
What should I do if I want my first script (the one without the timeout) to set the model to undefined because its value is not in the md-option values?
Are these behaviors documented somewhere?
What are the rules?
well finally I've found the answer in angular doc...
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
It's the fact that the validity state changes from true to false when the field is set to required.

Why is $location.absUrl(), $location.$$url, $location.$$path blank in href?

Here is the code in concern:
<div ng-app="">
https://www.facebook.com/sharer/sharer.php?u={{$location.absUrl()}}
https://www.facebook.com/sharer/sharer.php?u={{$location.$$url}}
https://www.facebook.com/sharer/sharer.php?u={{$location.$$path}}
</div>
We need the value of the u parameter to be current page.
Where are we wrong?
You cannot do that in HTML, alternatively you can get the current location like this,
Assign the curren location to a scope variable,
$scope.a = window.location.href;
Then in HTML,
<br>Link = <a ng-href="https://www.facebook.com/sharer/sharer.php?u={{a }}" target="_blank">facebook</a>
DEMO
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('TestCtrl', ['$scope', function($scope) {
$scope.a = window.location.href;
}]);
</script>
</head>
<body ng-app="myApp">
<div ng-controller="TestCtrl">
<input type="text" ng-model="a">
<br>a={{a}}
<br>
<br>Link = <a ng-href="https://www.facebook.com/sharer/sharer.php?u={{a}}" target="_blank">facebook</a>
</div>
</body>
</html>
The property which are present of $scope variable those are only available to use on HTML as binding. So $location service you have to expose on $scope
//inject $location to controller before use it.
$scope.$location = $location;

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
}
];
}]);

Updating a variable inside Service

Right I've got a really dumb one for you, and I've been looking at this code all day with no result.
I have a simple textbox which goes through a controller and updates a variable inside a service (The service will eventually fetch/update data from somewhere else).
At the moment, I am able to retrieve the variable value all the way to the view and it works, but the textbox is unable to update the variable inside the service in order to then display the new variable value in the view again....
I really appreciate any help and hope I have made sense!!!
// APP/APP.JS
(function(){
var app = angular.module('appMod', ['ngRoute', 'ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'introController',
templateUrl: 'app/partials/intro.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('nameController', function($scope, dataService) {
var nameValue;
this.name = dataService.getName();
this.submitName = function(nameVal) {
nameValue = this.nameCtrl.nameVal;
dataService.setName(nameValue);
};
});
app.controller('introController', function($scope, dataService) {
this.name = dataService.getName();
});
app.service('dataService', function () {
var name = "f";
this.getName = function() {
return name;
};
this.setName = function(nameVal) {
name = nameVal;
};
});
})();
<!-- INDEX.HTML -->
<!DOCTYPE html>
<html ng-app="appMod">
<head>
<link rel="stylesheet" type="text/css" href="content/css/normalize.css">
<link rel="stylesheet" type="text/css" href="content/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/style.css">
<link rel="stylesheet" type="text/css" href="content/css/animation.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.min.js"></script>
<script type="text/javascript" src="scripts/angular-timer.min.js"></script>
<script type="text/javascript" src="scripts/angular-animate.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body>
<div class="container">
<div class="row" ng-controller="nameController as nameCtrl">
<img src="content/images/sitelogo.png" class="logo">
<h2 class="welcomeMessage fade">Welcome <span class="fade" ng-show="!nameCtrl.name == ''">{{nameCtrl.name}}</span><span class="inline fade" ng-hide="nameCtrl.name !== ''">Friend</span> <small>(We like to get personal!)</small></h2>
<div class="namebox fade">
<h2>Welcome <small class="fade">Please type your name</small></h2>
<form class="fade">
<div class="form-group">
<input type="text" class="form-control" ng-model="nameCtrl.nameVal" autofocus>
</div>
<button type="submit" style="width:100%;" class="btn btn-default fade" ng-click="nameCtrl.submitName()" >Submit</button>
</form>
</div>
</div>
</div>
<div ng-view></div>
</body>
</html>
You need to be binding to name and not nameVal on your input
Then just pass that in your setName call, i don't think the rest of the code is needed in there, you can get rid of the nameValue var too.
this.submitName = function() {
dataService.setName(this.name);
};
The nameValue var is local to the controller and not available on the $scope to bind to your view, so even though you were changing it, the view didn't know about it as it couldn't see that var.

Add CSS to a div using a function in knockoutJS

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());

Categories

Resources