访问ng重复作用域

Accessing ng-repeat scope

本文关键字:作用域 ng 访问      更新时间:2023-09-26

我有一个项目列表,当用户点击它们时,这些项目会高亮显示(使用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

有关更多详细信息,请查看有关继承和作用域的链接