1
myApp.controller("MyCtrl",function ($scope) {
    $scope.value1= '0';
    $scope.$watch('value1', function(value) {
    alert(value);
     });
 });

JS Code:

var myApp = angular.module('myApp',[]);    
function MyCtrl($scope) {
    $scope.value1= '0';

    $scope.$watch('value1', function(value) {
       alert(value);
    });
}

HTML Code:

<div ng-controller="MyCtrl">
<span ng-repeat="i in [0, 1, 2]">
  <input name="asdf" ng-model="value1" value="{{i}}" type="radio">
</span>    
<hr> 
{{value1}}
</div>

Alert shown on loading only. After that value1 showing initial value only i.e 0.

Demo

1
  • You have to register the controller with your angular app Commented Jan 2, 2015 at 9:11

1 Answer 1

5

Its actually the problem of scope. I've modified the example here at http://jsfiddle.net/ucf02Lxz/2/. Have a look. Basically you need to use an object to modify the value at parent scope.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    // an object to prevent problem
    $scope.data = {};
    $scope.data.value1 = '0';

    $scope.$watch('data.value1', function(value) {
       alert(value);
    });
})

<div ng-controller="MyCtrl">
    <span ng-repeat="i in [0, 1, 2]">
        <input name="asdf" ng-model="data.value1" ng-value="i" type="radio" />
    </span>    
    <hr /> 
    {{data.value1}}
</div>

Read more at https://github.com/angular/angular.js/wiki/Understanding-Scopes

Sign up to request clarification or add additional context in comments.

2 Comments

I know you have the link there, but it might be worthwhile adding a short summary to the answer? E.g. This is a caveat related to JavaScript and not AngularJS: The ng-repeat creates its own child scopes which prototypically inherit from the parent scope. Any writes/sets to inherited primitive values (like string, number, boolean) on child objects will only set the value on the child object and not the parent object.
@ReinardMavronicolas You are absolutely correct. Thank you for pointing it out. I'll modify the answer to include more data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.