[英]ng-click with ng-repeat not working with direct expressions (not functions)
I am having an ng-repeat block and with it i am writing an ng-click with a direct expression of setting a $scope variable to true.. but it doesn't work.. can someone plz help.. here is the plnkr 我有一个ng-repeat块,并用它直接写一个ng-click,将$ scope变量设置为true ..但是它不起作用..有人可以帮忙..这是plnkr
HTML : HTML :
selected: {{selected}}
<ul>
<li ng-repeat="t in t.header" ng-click="selected = true;">{{t.a1}}</li>
</ul>
JS : JS :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.selected = false;
$scope.t = {
header: [
{
a1:'a1'
},
{
a1:'a1'
}
]
}
});
for now i am having a workaround to have a function call on its click and set the variable that is required, but curious to know whats wrong with the other approach? 现在,我有一个解决方法,可以在其单击上调用函数并设置所需的变量,但想知道另一种方法有什么问题吗?
It's working, but because of the ngRepeat, selected is binded to the new scope. 它正在工作,但是由于ngRepeat,selected被绑定到新作用域。 You can instead put selected in an object, so it won't create a new selected property on the child scope:
您可以将selected放置在对象中,这样就不会在子作用域上创建新的selected属性:
<li ng-repeat="t in t.header" ng-click="selectedObj.selected = true;">{{t.a1}}
$scope.selectedObj = { selected: false };
Try this: 尝试这个:
//$scope.selected = false;
$scope.model = {};
$scope.model.selected = false;
What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. 发生的情况是子作用域获得了自己的属性,该属性隐藏/阴影了同名的父属性。 This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.
AngularJS并没有这样做-这就是JavaScript原型继承的工作方式。
For better understanding: https://github.com/angular/angular.js/wiki/Understanding-Scopes 为了更好地理解: https : //github.com/angular/angular.js/wiki/Understanding-Scopes
Just use $parent scope, like this: 只需使用$ parent范围,像这样:
<li ng-repeat="t in t.header" ng-click="$parent.selected = true;">
Every item in ng-repat has his own scope. ng-repat中的每个项目都有自己的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.