Why the inputs are not working right with ng-repeat [duplicate]

家住魔仙堡 提交于 2019-11-27 09:51:27

Because ng-repeat does create a new child scope(prototypically inherited) on each iteration when it repeats a template on wherever ng-repeat directive has been placed.

So what happens when ng-repeat creates a new prototypically inherited child scope?

In the child scope it carries all properties in which primitive property initial value taken while creating child scope & object values are taken with their references so update in parent scope value will update in child scope value & vice versa.

Here in your case you had ng-model="kindSelected" variable inside ng-repeat so that scope variable got create inside the ng-repeat scope and doesn't available outside ng-repeat directive.

To fix such a problem you could use object while defining ng-model so that you could follow Dot rule while defining ng-model. That means you could define a object called as $scope.model inside controller & then add kindSelected property so that the value will get updated on selection of checkbox.

Markup

<div ng-repeat="kind in movieKinds">
    <input type="radio" name="movies" ng-value="kind" ng-model="kindSelected"> {{kind.name}}<br>
</div>
Selected Movie :{{model.kindSelected}}

Code

$scope.model = {};

The other way to fix this problem is to use controllerAs syntax which will use alias of controller so the scope hierarchy related problem doesn't happen on HTML. Whichever controller variable you want you could use that alias of the controller.

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