richbai90
richbai90

Reputation: 5204

check if there are any directives on a controller

I would like to build a service that could check if there were any directives in use on a controller and if so build a directives object and populate it with objects for each directive on the controller. The benefit of this would be that I could build a type of API for scope inheritance automatically for all of my directives. Right now I'm essentially doing the same thing but by hand. Is there some property on the scope object that I can use to find the names of directives in use? Here's an example of what I mean

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>

In this way I can share the scope without polluting the parent scope. So my question is, rather than having to build the directivesAPI by hand I'd like to be able to do something more like this

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.
}]);

If anyone has any ideas I'd love to hear them.

Upvotes: 0

Views: 39

Answers (1)

pje
pje

Reputation: 2468

So, from what I understand, what you want is to be able to have a common "scope" that you can use between all of your directives?

If that's the case, then what you could do instead is simply create a service. You could use the service across all of your directives, and treat it as if it were a private "scope". Something like what I have below:

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;
});

You can use $injector to get the service in your directive. See the answer to AngularJS. Passing Service as an argument to Directive.

Upvotes: 1

Related Questions