如何将范围限制为单击的元素?

时间:2014-10-28 21:03:19

标签: javascript angularjs angularjs-scope

我有一个简单的AngularJS应用程序,我想用它来按标签过滤搜索结果。第一步,我正在创建一个过滤器链接列表,用于切换单个标签的可见性。问题是点击一个链接可以切换列表中所有链接的状态

我意识到这可能需要为我的最终目标进行重构,但我想首先了解这里发生的事情。如何将范围限制为单击的元素?

HTML:

<ul ng-app="myApp" ng-controller="myCtrl">
    <li><a href="" ng-click="toggleSelected()">
        <span class="glyphicon" 
          ng-class="{'glyphicon-check': selected, 'glyphicon-unchecked': !selected}">
        </span> Office Productivity
    </a></li>

    <li><a href="" ng-click="toggleSelected()">
        <span class="glyphicon" 
          ng-class="{'glyphicon-check': selected, 'glyphicon-unchecked': !selected}">
        </span> Leadership
    </a></li>

    ...
</ul>

JavaScript:

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', function ($scope) {

    // toggle the selected state of an element scope, with a default of true
    $scope.toggleSelected = function () {
        $scope.selected = $scope.selected ? !$scope.selected : true;
        return $scope.selected;
    };
});

Fiddle

1 个答案:

答案 0 :(得分:3)

我重构了你的代码,从控制器获取清单。然后我循环遍历这些对象,并在ng-click中使用属性(复选框的标题)调用toggleSelected

以下是经过编辑的jsFiddle:http://jsfiddle.net/otprj3du/3/

我将此添加到范围中:

$scope.checkBoxes = {
    'Office Productivity':0,
    'Leadership':0,
    'Communication Skills':0,
    'HR & Compliance':0,
    'Career Readiness':0,    
};

并像这样呈现列表:

<li ng-repeat="(title,selected) in checkBoxes">
    <a href="" ng-click="toggleSelected(title)">
        <span class="glyphicon" 
          ng-class="{'glyphicon-check': selected, 'glyphicon-unchecked': !selected}">
        </span> 
        {{ title }}
    </a>
</li>

在toggleSelected中,我只是编辑了$scope.checkBoxes

$scope.toggleSelected = function (title) {
  $scope.checkBoxes[title] = $scope.checkBoxes[title] ? !$scope.checkBoxes[title] : 1;
};