访问ng重复作用域
Accessing ng-repeat scope
我有一个项目列表,当用户点击它们时,这些项目会高亮显示(使用selectedData类)。
<div>Remove highlight </div>
<ul>
<li ng-repeat="data in inputData">
<span title="{{data}}" ng-class="selected ? 'selectedData' : ''" ng-click="selected = !selected;">
{{data}}
</span>
</li>
</ul>
当我点击列表外的清除按钮时,我想删除所有列表项的亮点(inturn删除selectedData类),换句话说,为每个<li>
重置selected
。由于ng repeat创建了自己的作用域,我该如何实现这一点。
试试这个:
<li id="list"... ng-repeat...>
<span ng-class="selected: selected[$index] ? 'selectedData' : ''" ng-click="selected[$index] = !selected[$index]">
</li>
function clear() {
for (i = 0; i < selected.length; i++) {
selected[i] = false;
}
}
@Sidharth Panwar的答案基本上是正确的
但我不确定<span ng-class="selected: selected[$index] ? 'selectedData' : ''"
中是否需要selected:
,我设法使其仅与三元运算符一起工作:
// Code goes here
angular.module("app",[])
.controller("controller", function($scope){
$scope.selected=[]; // <--- this is the most important part of the solution
$scope.clearSelector = function(){
for(var i = 0; i < $scope.selected.length; i++){
$scope.selected[i] = false;
}
};
});
.highlight{
color:red;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@*" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
</head>
<body ng-controller="controller">
<ul ng-init="temp=[1,2,3]">
<li ng-repeat="i in temp" ng-click="selected[$index] = !selected[$index]" ng-class="selected[$index]?'highlight':''">
toggel between black and red
</li>
</ul>
<button ng-click="clearSelector()">clear</button>
</body>
</html>
如果您担心ng-repeat
有自己的作用域,并且您不能从父作用域("清除"按钮所在的位置)操作其值,则在父作用域中创建数组可以帮助您集中控制变量:
// both in child scope
selected=1; // create a new variable if no existing variable named
//"selected" in the current scope,
// this happens when javascript knows how to create stuff ie:primitives
selected[0]=1; // need to know the address of "selected", if we can't
// find it in the current scope, look it up in the parent scope
有关更多详细信息,请查看有关继承和作用域的链接
相关文章:
- 从ng模板访问作用域
- ng重复中的ng模型-初始化唯一作用域属性
- 如何为通过ng-view指令或ng-controller指令创建的每个新作用域设置侦听器
- ng根据作用域值隐藏
- 阻止“ng include”创建孤立的作用域.AngularJS
- 角度指示ng重复作用域和服务
- 以新模式访问作用域形式ng repeat
- AngularJS select with ng选项不更新父作用域中的引用对象属性
- AngularJS:将ng重复作用域暴露给ng transclude
- 使用ng repeat中的键值来扩展作用域表达式
- ng隔离未附加到templateUrl的作用域
- 如果在具有单独作用域的其他指令中,请使用ng
- 具有ng模型依赖性的孤立作用域陷阱
- 通过json动态绑定作用域到ng模型
- 如果作用域值等于单击的元素的属性值,则Ng类
- 使用ng-click在作用域内定位元素
- 如何在使用ng repeat时停止传播(或者如何更好地隔离作用域)
- AngularJS ng-click不调用作用域上的函数
- AngularJS从外部访问作用域ng-repeat
- $http承诺不更新作用域(ng-hide)