单选按钮值更改在AngularJS中不起作用

时间:2015-01-02 08:58:15

标签: javascript angularjs

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

JS代码:

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

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

HTML代码:

<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>

仅在加载时显示警报。之后value1仅显示初始值,即0

Demo

1 个答案:

答案 0 :(得分:4)

它实际上是范围问题。我在http://jsfiddle.net/ucf02Lxz/2/修改了示例。看一看。基本上你需要使用一个对象来修改父范围的值。

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>

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

了解详情