2016-02-25 105 views
1

Angular入门并且遇到问题让模型绑定可用于模板中的选择选项。Angular - ngOptions模型值不更新

我有以下的NG-选项中选择一个模板:

<select ng-model="listenercount" ng-options="n for n in [] | range:0:1000" ng-change="listenersUpdate()"></select> 

我有过滤器,看起来像这样:

angular.module('myapp').filter('range', function() { 
    return function(input, min, max) { 
     min = parseInt(min); 
     max = parseInt(max); 
     for (var i=min; i<max; i++) { 
      input.push(i); 
     } 
     return input; 
    }; 
}); 

我的选择正确显示了基于期权0-1000我的过滤器。

在我的控制,我有以下:

$scope.listenercount = 0; 

$scope.listenersUpdate = function() { 
    alert('new listener count is now:' + $scope.listenercount); 
} 

我警报消息每次我改变选择按预期时间弹出,但它总是显示$ scope.listenercount = 0 $ scope.listenercount模型绑定似乎不会更新值。

任何明显的我做错了?

+0

你在浏览器控制台的任何错误? – csharpfolk

+0

好问题..浏览器的JavaScript控制台中没有错误。 –

+0

你可以发布整个控制器代码吗? – csharpfolk

回答

0

<body ng-app="myapp"> 
 
    <script> 
 
    angular.module('myapp', []) 
 
    .controller('ExampleController', ['$scope', function($scope) { 
 
     $scope.listenercount = 0; 
 

 
$scope.listenersUpdate = function() { 
 
    alert('new listener count is now:' + $scope.listenercount); 
 
} 
 

 
    }]); 
 
    angular.module('myapp').filter('range', function() { 
 
    return function(input, min, max) { 
 
     min = parseInt(min); 
 
     max = parseInt(max); 
 
     for (var i=min; i<max; i++) { 
 
      input.push(i); 
 
     } 
 
     return input; 
 
    }; 
 
}); 
 
</script> 
 
<div ng-controller="ExampleController"> 
 
    <select ng-model="listenercount" ng-options="n for n in [] | range:0:1000" ng-change="listenersUpdate()"></select> 
 

 
    <tt>debug = {{confirmed}}</tt><br/> 
 
    <tt>counter = {{counter}}</tt><br/> 
 
</div> 
 
</body>

这正按预期

+0

嗯..当我使用{{listenercount}}在我的模板中显示选定的值时,只要我更改选择值,页面就会在浏览器中更新。然而,我的控制器仍然显示$ scope.listenercount为0. 我改变了我的控制器使用console.log而不是警告每个另一个建议,这并没有改变任何东西。 –

+1

@John我的猜测是你的select和你的{{listenercount}}是在ng-if或者ng-repeat或者任何指令中创建自己的作用域。发布一个plunkr重现错误 –

+0

我添加了一个setInterval计时器来输出我的$ scope.listenercount到console.log,它永远不会改变。不管我改变选择。 必须与我的ng-model ='x'的某些语法原因没有绑定到$ scope.x。没有?? –