user3427540
user3427540

Reputation: 1172

why ng-Value is not working with simple variables?

This code works great. When we select the radio button it display the value.

 <script type="text/javascript">
var sampleApp = angular.module("sampleApp",[]);
sampleApp.controller('sampleCtrl', ['$scope', function($scope){
    $scope.names = ["a","b","c","d","e"];
    $scope.beststudent = {studName: "d"};
}])
</script>

<ul>
  <li ng-repeat="name in names">
    <input type="radio" name="sudents" ng-model="beststudent.studName" ng-value="name">     {{name}}
 </li>
</ul>
Selected Value is: {{beststudent.studName}}

But this is not working when i declare beststudent like this,

$scope.beststudent = "d";

and

<input type="radio" name="sudents" ng-model="beststudent" ng-value="name">{{name}}

Why do I need the values in key-value pair?

Upvotes: 0

Views: 2340

Answers (1)

gkalpak
gkalpak

Reputation: 48211

It's because of how scopes work and because ngRepeat will create a new child-scope for each <li>.

If you use an object for $scope.beststudent (e.g. {studName: 'd'}), then the child-scope will update the parent-scope's beststudent property.
If you use a primitive (e.g. string) for $scope.beststudent (e.g. 'd'), then each child-scope will create a local variable named beststudent (and not update the parent-scope's property).

This is basically because of how JavaScript's prototypal inheritance works (it's not Angular specific).

Upvotes: 2

Related Questions