Error in retrieving value of dynamic ng-model - javascript

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

Related

How to Access Internal script $scope value in controller function in angular JS

Here is HTML with internal script
<html>
<body ng-controller="test">
<span> {{data.name}} </span>
<input ng-model="data.name">
<hidden id="test" ng-hide="true"></hidden>
</body>
<script>
var $scope = angular.element(document.getElementById('test')).scope();
$scope.data = {
name : test;
};
<script>
</html>
Here is Controller
app.controller('test', function($scope) {
$scope.data = {};
console.log($scope.data.name) //outputs undefined
})
I want internal script data into the controller. It prints undefined. I defined an object in the controller but updated in the internal script. If suppose I print or bind data from HTML, it does not get updated in the controller scope object. Any Solution for this?
Did you try to fetch it from the controller? Or maybe you will need a more angularjs approach. I created two examples: one for initializing the data in the controller, and one to console.log the niceLittleValue.
(function(angular) {
'use strict';
var myApp = angular.module('niceExample', []);
myApp.config(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
}]);
myApp.controller('test', ['$scope', function($scope) {
$scope.data = [];
$scope.data.name = 'test';
$scope.data.anotherTest = angular.element(document.querySelector('#anotherTest'));
console.log($scope.data.anotherTest[0]);
}]);
})(window.angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html ng-app="niceExample">
<body ng-controller="test">
<input ng-model="data.name" ng-model-options="{debounce: 500}">
<span> {{data.name}} </span>
<hidden id="test" ng-hide="true"></hidden>
<hidden id="anotherTest" value="niceLittleValue" ng-hide="true"></hidden>
<span> {{data.anotherTest}} </span>
</body>
</html>

Angular expression send by id

On Select/Option onchange() event it should write the value of the JSON file as an angular expression to test ID div.
However it writes like it's just a string: {{names[1].thnev}}
(And if I put this manually into the ID div, it works.)
Can you help me what did I miss? (In the last 4 hours...)
Thank you.
<div ng-app="myApp" ng-controller="customersCtrl">
<select id="thaz" name="thaz" class="selectbox" onchange="onChange(this.value)">
<option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
</select>
<div id="list"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("al_list_th.php")
.then(function (response) {$scope.names = response.data.records;});
});
function onChange(value) {
document.getElementById("list").innerHTML = "{{names[" + value + "].thnev}}";
}
</script>
We can use the built-ins that AngularJS has available to simplify the problem.
In this case, we can use ngModel to bind the value of the select into a variable that we can use in our template. Let's call this variable selectVal.
Then, we can write {{names[selectVal].thnev}} directly inside of the div that we want this output to live in.
I've put together this example to show the changes:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.selectVal = "default";
$scope.names = [{id: 0, thnev: 5}, {id: 1, thnev: 6} ];
//$http.get("al_list_th.php")
//.then(function (response) {$scope.names = response.data.records;});
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<select id="thaz" name="thaz" class="selectbox" ng-model="selectVal">
<option value="default">None</option>
<option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
</select>
<div id="list">
{{names[selectVal].thnev}}
</div>
</div>
Note: In my code I added an extra option so that there would be a default as opposed to a blank initial dropdown. You don't have to do this -- the code will work the same without it.

Strict ng-model value in Angularjs

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 === '') {
...
}
}

How to get the value of a custom attribute in angular js

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>

Execise angularJS windows alert not woring

i've a simple problem, i've copied and pasted some code and i'd like to show an alert with a value inside it. I'm just learning angular and the fuction works (i've places a console log inside it and it is executed), but the window.alert doesn't appear.
I've read this tutorial and tried changing the name of variable but it's still not working. In the online tutorial of angual everything is going fine so where is my mistake?
Here is the page code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<script type="text/javascript" charset="utf-8" src="greetings.js"></script>
</head>
<body>
<h1>Greetings</h1>
<div ng-app="greetings" ng-controller="GreetingsController as greeting">
<b>Greetings:</b>
<div>
Name: <input type="text" min="0" ng-model="greeting.name" required >
</div>
<div>
FamilyName: <input type="text" ng-model="greeting.familyName" required >
<select
data-ng-options="c for c in greeting.tipi" data-ng-model="greeting.selectedOption">
<!--<option ng-repeat="c in greeting.tipi">{{c}}</option>-->
</select>
</div>
<div>
<b>Greeting:</b>
<span>
{{greeting.total(greeting.selectedOption)}} {{greeting.name}} {{greeting.familyName}}
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
<br/>
</span>
</div>
</div>
</body>
</html>
Here is the controller code greetings.js:
angular.module('greetings', [])
.controller('GreetingsController', function() {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
To use an Angular service, you add it as a dependency for the component (controller, service, filter or directive) that depends on the service.
And $window is a service.
you should add the parameter or the dependency $window to use this service.
angular.module('greetings', [])
.controller('GreetingsController', ['$window', function($window) {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
}]);
You need to include $window in your dependencies, or else your controller reads it as undefined.
Try the following:
angular.module('greetings', [])
.controller('GreetingsController', function($window) {
//Rest of your code
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
I added $window as a parameter to the function of your controller.
the problem was in the html code:
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
should have been:
<button class="btn" ng-click="greeting.greet(greeting.selectedOption)">Greet</button>

Categories

Resources