当我在angularjs中使用.scope()时会发生什么?

What is happening when I use .scope() in angularjs?

本文关键字:什么 scope angularjs      更新时间:2023-09-26

有人可以解释发生了什么,当我使用。scope()指令内?

我有一个指令,被分配创建一个正方形的网格。加载时,我希望这些方块是可点击的,所以我赋值了

ng-click="disabled || add($index)"

,然后在link: function () {}中我运行:

scope.add = function (index) {
     scope.disabled = true;
}

,以便在单击时禁用它们。

然后我有一个服务,它获取被点击的其中一个框的索引,运行一些逻辑,然后返回其他可能可点击的方块。服务返回索引数组,例如:[2,5,6,7]

然后我取这个数组,循环遍历它,并将这些框赋值为可点击的,通过它们的索引:

for (var x = 0; x < arr.length; x++) {
    var nScope = el.children().eq(arr[x]).scope();
    nScope.disabled = false;
}

之后,当上面的另一个元素被点击时,原来的scope.disabled = true;被忽略,而我在循环中设置的那些元素仍然是可点击的…为什么呢?当我运行上面的.scope()时发生了什么,以及我如何刷新网格,使其无法再次点击,直到服务带着更多可能的移动回来?

当然,如果有更合适的方法,请分享。

编辑:

在注释中添加更多代码:

HTML模板:

<div 
    class="cell" 
    ng-click="disabled ||  addItem($index)" 
    ng-disabled="disabled" 
    ng-repeat="cell in ngModel.grid track by $index">{{item}}</div>

指令的设置如下:

return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        ngModel: '='
    },
    templateUrl: 'scripts/grid/grid.html',
    link: function () {
        //code above goes here
    }
}

服务有它正在做的各种事情,其中之一是根据最初被点击对象的索引提供可能被点击的对象。出于这个问题的目的,我省略了服务代码,因为到目前为止我唯一的问题是弄清楚.scope()到底在做什么,以及如何利用它来发挥我的优势。

这并不能完全回答您的问题,但可以作为您构建的一种方法。

查看此提琴:http://jsfiddle.net/HB7LU/4553/

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

myApp.service('myService', function() {
    return{
        saveBox: function(id)
        {
        alert('gonna update box with id: '+id);
        }
    }
});

myApp.directive('boxgenerator', ['myService', function(myService) {
    return {
        template: '<div class="box {{status}} -  {{id}}">{{status}}</div>',
        scope:{
            id: '@id',
            status: '@status'
            },
    link : function(scope, element, attrs) 
        {
            element.bind("click",function(){
               save = myService.saveBox(scope.id);
               scope.status = 'disabled'; 
               scope.$apply();
            });
        }
    }
}]);

function MyCtrl($scope) {
    $scope.boxes = [];
    $scope.box = { status: 'enabled' };
    for (i = 0; i < 9; i++)
    {
       $scope.boxes.push($scope.box);
    }
}