首页 > directive的依赖的全局数据应该集中放在哪里比较好?

directive的依赖的全局数据应该集中放在哪里比较好?

说明:写一个direcitive,实现点击选中所有的checkbox,现在有个问题就是好多个模版中都会用到
这个directive,那我必须在控制器上手动创建一个变量去存储(例子中是selectall),这样子有点分散,
能不能把放在一个单独的环境里。
比如使用value图纸,或者有没有其他更好的实现方法。

<!--这里是html文件-->
<div ng-controller="UserController">
....
    <li select-all status="selectall">全选</li>
......
    <input type="checkbox" ng-model="selectall">
...
</div>
//js 文件
var directive  = angular.module("directive",[]);
directive.directive("selectAll",function(){ 
    function link(scope,element,attrs){
        var span = element.find(".ng-scope");
         element.click(function(){
            scope.status = !scope.status;
            span.html(scope.status ? '反选' : '全选');
            scope.$apply();
        });
    }
    return {
        scope : {
            status : "=",
        },
        link : link,
        restrict : "A",
        transclude : true,
        template : "<span ng-transclude></span>"
    }
});

你把这部分当做一个模块,然后在哪里需要了,就把它当做一个依赖,注入到你所需要使用的那个模块中就好了。

我大概明白你的意思,就是说服务器端返回来的一个数据,需要在多个控制器中使用,是这样吗?
那么我觉得可以这样:
首先你可以创建一个服务:

javascriptangular.module("MyServiceData", [])
.factory("dataService", [function(){...}]);

可以让数据保存在这个服务里面,然后在你的app中,注入这个服务:

javascriptangular.module("MyApp", ["MyServiceData"])
.controller("MyController", function(dataService){
//在这里使用dataService的数据
}]);

这样应该可以吧。


在依赖的时候注入$rootscope,然后添加到这里,虽然有点污染。不知有没有其他不好的地方。

【热门文章】
【热门文章】