检查控制器上是否有任何指令

时间:2014-06-06 20:03:30

标签: javascript angularjs

我想构建一个服务,可以检查控制器上是否有任何指令正在使用,如果是,则构建一个指令对象并用控制器上每个指令的对象填充它。这样做的好处是我可以为我的所有指令自动构建一种用于范围继承的API。现在我基本上是做同样的事情,但是手工完成。我可以使用范围对象上的某些属性来查找正在使用的指令的名称吗?这是我的意思的一个例子

app.controller('controller1' ['$scope', function($scope) {
    $scope.directivesAPI = {};
    $scope.directivesAPI.privateScope = {};
}]);


app.directive('privateScope', function() {
    restrict: A,
    scope: true,
    link: function(scope, elem, attr) {
        scope.directivesAPI.privateScope.what = "My Job is to provide new features";
        scope.directivesAPI.privateScope.how = "I share the scope using this fancy API";

    }
})


<div ng-controller="controller1" privateScope>
    {{directivesAPI.what}}
    {{directivesAPI.how}}
</div>

通过这种方式,我可以共享范围而不会污染父范围。所以我的问题是,我不想手工构建指令API,而是希望能够做更像这样的事情

app.controller('controller1' ['$scope', 'directivesAPI' function($scope,directivesAPI) {
    $scope.directivesAPI = directivesAPI.build();

    //The service is responsible for finding the directives and building the object for me.
}]);

如果有人有任何想法,我很乐意听到。

1 个答案:

答案 0 :(得分:1)

所以,根据我的理解,你想要的是能够有一个共同的范围&#34;您可以在所有指令之间使用吗?

如果是这样,那么你可以做的只是创建一个服务。您可以在所有指令中使用该服务,并将其视为私有&#34;范围&#34;。像我下面的东西:

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

myApp.controller('GreetingController', ['$scope', 'myPrivateScope',
  function($scope, myPrivateScope) {
    $scope.greeting = myPrivateScope.greeting;
  }
]);

myApp.service('myPrivateScope', function () {
  var srv = {};

  srv.greeting = 'Hola!';

  return srv;
});

您可以使用$injector在指令中获取服务。请参阅AngularJS. Passing Service as an argument to Directive的答案。