ng-change event only fires once for each radio button when created with ng-repeat

和自甴很熟 提交于 2019-12-05 01:12:07
tasseKATT

Use an object instead of a primitive value:

app.controller('mainController', ['$scope', function (scope) {
  scope.environment = { value: '' };
}]);

Remove ng-change and $watch. ng-model will be enough (unless I'm misunderstanding the use case).

Demo: http://jsfiddle.net/GLAQ8/

Very good post on prototypal inheritance can be found here.

gkalpak

The cause of the problem is that ngRepeat will create new scopes for its children (along with how prototypal inheritance affects scopes).

The Angular wiki has a fairly good (and thorough) explanation of how scope inheritance works (and the common pitfalls).

This answer to a very similar (in nature) problem pretty much explains the issue.

In your specific case, you could introduse an object (e.g. local) and assign environment as its property):

scope.local = {environment: scope.environment};
scope.changeEnvironment = function(choice) {
    scope.environment = choice.id;
};

Then you should bind your template to that "encaplulated" property:

<input ... ng-model="local.environement" ... />

See, also, this short demo.


UPDATE

This answer intends to point out the root of the issue.
A different implementation (like the ones proposed by tasseKATT or Leon) is definitely recommended (and way more "Angularish").

you are using enviorement instead of $parent.enviorement in your ng-change event which is tied to the repeat scope not the the ng-repeat parent scope where the enviorement variable lives,

http://jsfiddle.net/cJ4Wb/7/

ng-model="$parent.enviroment"

notice that in this case you don't even need the events to keep enviorement updated and any changes in the model will refelct in the radio buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!