How to assign strict value to ng-model, so that "" not equal to false. and radio got deseleted when names equals ""
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ''
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="radio" ng-model="names" ng-value="false" >select only when model is false not ""
</div>
</body>
</html>
Not sure what exact behavior you are looking for but, you could put a function in ng-checked that takes names as an argument to implement the behavior you want.
input tag
ng-checked="myValue(names)"
controller
$scope.myValue = function(names) {
if (names === '') {
...
}
}
Related
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.
<div ng-controller="myCon" test="abc"></div> then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.
<div ng-controller="myCon">
<div test="def"></div>
</div>
In this case I got undefined in alert($attrs.test)
Full code...
<html>
<script src="angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
alert(JSON.stringify($attrs.test)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>
app.directive("test", function() {
return {
restrict: "A",
scope: {
text: "#test"
}
};
});
Update your directive scope and add restrict . For better understanding refer to this question
You can check it:
<html>
<script src="src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js""></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
var testa=$scope.test;
alert(JSON.stringify(testa)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>
You can get the element on click if you pass $event in ng-click, i.e. ng-click="check($event)" and can get the attribute from $event.target.
Check fiddle : https://jsfiddle.net/ayusharma/xb63g9ca/
JS
app.controller('myCtrl', function($scope) {
$scope.clickMe = function(evt) {
console.log(evt.target.getAttribute('test'))
}
});
HTML
<div ng-controller="myCtrl">
<div ng-click="clickMe($event)" test="abc">Click on Me</div>
</div>
I would like to know in the below example how can i check whether entered value in input field is already available or not.
I have an input field, on key press i want to check the input field value with the values from names array and display error message down if value is already present in names array and also disable the button. If value entered is not present in the names array i dont want to display error message and enable the Add button. Here is the plunkr - https://plnkr.co/edit/rz0tjxhEajz7848Ws3ig?p=preview
html -
<!DOCTYPE html>
<html>
<head>
<script src="angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="test" ng-controller="testController">
Name: <input type="text"/>
<button on-keypress="submit()">Add</button>
</body>
</html>
script -
var testController = angular.module('test', []);
testController.controller('testController', ['$scope', function($scope) {
$scope.names = ["name1","name2","name3"];
angular.forEach($scope.names, function(x) {
console.log(x);
});
}]);
Instead of looping through the array each time , use ng-change and check for duplicate using array.prototype.includes().
Updated Plunkr
Html:
<body ng-app="test" ng-controller="testController">
Name: <input type="text" ng-change="checkName()" ng-model="name"/>
<button ng-keypress="submit()">Add</button>
<p ng-show="showError">Name already exists</p>
</body>
Controller:
$scope.names = ["name1","name2","name3"];
$scope.showError = false;
$scope.checkName = function (){
if($scope.names.includes($scope.name)){
$scope.showError = true;
} else {
$scope.showError = false;
}
}
<body ng-app="test" ng-controller="testController">
Name: <input type="text" id="getValue"/>
<button on-keypress="submit()">Add</button>
</body>
Added id above to retrieve value from text field
$scope.names = ["name1","name2","name3"];
for (i = 0; i < $scope.names.length; i++) {
if (document.getElementById('getValue').value === $scope.names[i]) {
alert('something');
return;
};
};
Then ran a function to check for names in array and if there alert and stop function.
To hide add class to <button on-keypress="submit()" class="random">Add</button> and call from controller $('.random').hide();, note it's JQuery being used here.
I'm trying to set the dynamic property on a javascript object using the ng-model. But I'm unable to create it as I always get null for that property. I have different ways to copy the value from the variable self.username to self.params javascript object in the below code.
Please see this plnkr
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="//code.angularjs.org/1.2.26/angular.js"></script>
<script src="https://code.angularjs.org/1.2.26/angular-route.min.js">
</script>
<script src="app.js"></script>
<script src="routes.js"></script>
</head>
<body>
Carriers
<div class="mainContainer" ng-view></div>
</body>
</html>
routes.js
myApp.config(function($routeProvider) {
$routeProvider
.when('/carriers', {
templateUrl: 'carriers.html',
controller: 'MainCtrl',
controllerAs: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Carriers.html
<input type="text" placeholder="username" ng-model="mainCtrl.username" />
<button ng-click="mainCtrl.login()">Login</button>
app.js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function() {
var self = this;
self.username = '';
self.login = login;
self.params = {
username: self.username //doesnt work
};
//self.params.username=angular.copy(self.username); //doesnt work
//self.params['username']=self.username; //doesnt work
function login() {
// alert(self.username);
console.dir(self.username); // works
console.dir(self.params); // username:'' getting empty string for username property
}
});
The value does not update because you created a new object and set the value of self.params.username to the value of self.params. self.params.username does not reference self.params it was just set from the value when the object was created.
If you want to bind self.params.username to the input then you can change your input model to:
<input type="text" placeholder="username" ng-model="mainCtrl.params.username" />
Another alternative is to watch self.username and set the value of self.params.username to the new value using $watch
// watch mainCtrl.username for any changes
$scope.$watch('mainCtrl.username', function(newValue, oldValue) {
// set self.params.username from the new value
self.params.username = newValue;
});
I am working on a form having multiple radio button listings in which I will need to create dynamic ng-model for each of the radio button. I am being able to do that, but when same I am trying to retrieve in controller (USING the ng-model iteration with angular forEach loop) it seems model cannot be replicated with console.log. Anyone help?
HTML
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="radio" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]"><span>{{x.value}}</span>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques.val.id);
});
}
});
</script>
</head>
</html>
The Angular model is a JavaScript object itself. Instead of looping through the object, you can output the entire object to the console like this:
console.log( JSON.stringify($scope.dummy) );
To make it more easy to read and span multiple lines for complex objects, just add these arguments to stringify:
console.log( JSON.stringify($scope.dummy, null, 2) );
It also looks like you need a little work on how you handle the Radio buttons, I'll leave that to the excellent odetocode blog/site:
http://odetocode.com/blogs/scott/archive/2013/06/25/radio-buttons-with-angularjs.aspx
The main problem is that you're inside ngRepeat and it creates a child $scope, so to make it work, you should use or the Dot Rule or controller-as-syntax, as below:
$scope.model = {};
Then in your view:
<label>
<input type="radio" id="{{x.id}}" value="{{x.value}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
See it working:
(function() {
'use strict';
angular
.module('myApp', [])
.controller("myCtrl", function($scope) {
$scope.dummy = [
{
"name":"name1",
"value":"red",
"id":"id1"
},
{
"name":"name2",
"value":"blue",
"id":"id2"
},
{
"name":"name3",
"value":"yellow",
"id":"id3"
}
];
$scope.model = {};
$scope.ok = function() {
// With your original code:
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.model.Ques[val.id]); // <- note the syntax
});
// Or you can get all key / values stored in radio buttons:
/*for (var key in $scope.model.Ques) {
console.log('Key => ', key);
console.log('Value => ', $scope.model.Ques[key]);
}*/
}
});
})();
<!doctype html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<label>
<input type="radio" value="{{x.value}}" id="{{x.id}}" ng-model="model.Ques[x.id]">{{x.value}}
</label>
</p>
<button ng-click="ok()">Click</button>
</body>
</html>
For reference, check the #PankajParkar's answer.
Have a look at that.
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in dummy">
<input type="checkbox" name="{{x.name}}" id="{{x.id}}" ng-model="Ques[x.id]" />
<label>{{x.name}}</label>
</p>
<button ng-click="ok()">Click</button>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller
app.controller("myCtrl", function($scope){
$scope.dummy = [
{name:"name1",value:"red",id:"id1"},
{name:"name2",value:"blue",id:"id2"},
{name:"name3",value:"yellow",id:"id3"},
];
$scope.Ques = {};
$scope.ok = function(){
angular.forEach($scope.dummy, function(val, key) {
console.log($scope.Ques[val.id]);
});
}
});
It says in the docs that ngChange will not fire: "if the model is changed programmatically and not by a change to the input value".
Does this mean that if you ever change the model programmatically, you can't use ngChange?
Or does it mean that you can't use ngChange if:
1) You change the model programmatically
AND
2) You're unable to change the model via the input field
It just means that the ngChange expression won't be evaluated if javascript is used to change the model. If you wanted ngChange to fire you would need to programmatically call the expression similar to the following:
<input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
You would need to manually call the change function if you wanted it to fire:
$scope.confirmed = 'test';
$scope.change();
If I read and understand this correctly, unfortunatelly you can't do it with ng-change as you say, but I'm not 100% sure.
I was thinking about ng-model-options, a new feature that came with AngularJS 1.3 and maybe this can push you forward.
There is an automatical options for getters and setters that allows you to change the model in real time. Theoretically, you could use this and call your update function with ng-bind.
Maybe this can be your possible solution to solve your problem...
(function(angular) {
'use strict';
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
return angular.isDefined(newName) ? (_name = newName) : _name;
}
};
}]);
})(window.angular);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-ngModelOptions-directive-getter-setter-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="getterSetterExample">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</body>
</html>