当我在angularjs中使用.scope()时会发生什么?
What is happening when I use .scope() in angularjs?
有人可以解释发生了什么,当我使用。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);
}
}
相关文章:
- 这是什么 ==- javascript 运算符
- 我的单元测试选项是什么
- 全局变量和全局对象的属性之间有什么区别吗
- 打破承诺链的好方法是什么
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 什么's AngularJS中$scope.myScope=function()和function()之间的区别
- 在 AngularJS 中 !$scope.variableName 和 $scope.variableName 有什么
- $scope 在 angularJS/Ionic 中是什么意思
- 在 Angular.js 中更改视图时处理$scope状态和值的正确方法是什么?
- $scope.$emit 和 $rootScope.$emit 有什么区别
- 定义可能需要在AngularJS中修改$scope数据的实用程序/帮助程序方法的理想方式是什么
- 什么是`$scope$apply()不是't在调用堆栈中足够高意味着在这种反模式中
- $scope之间有什么不同吗$手表和$watch
- AngularJS中控制器的角色和$scope的角色是什么
- 如何准确地找出$scope中发生了什么变化$看
- 在服务场景中,在页面加载时设置$scope值的正确方法是什么?
- 当我在angularjs中使用.scope()时会发生什么?
- AngularJS中的$scope是什么?
- 在angularjs中获取$scope对象所有真值长度的最佳方法是什么
- 从工厂到$scope.什么是正确的方式