Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an angularjs Directive require Itself?

Can a directive require itself? Here's an example:

app.directive('menu', function () {
  return {
    restrict: 'E',
    require: '?^menu',
    link: function(scope, element, attrs, ctrl) {
      console.log('ctrl: ', ctrl);

      if (ctrl) {
        element.addClass('nested');
      } else {
        element.addClass('notnested');
      }
    }
  };
});

In my test it doesn't seem to work (ctrl is always undefined). See the plunk


BTW, after this question was answered I discovered that in this case the caret (^) has no effect and the controller passed to the link function is always the instance's own controller. [ plunk ]

like image 746
Gil Birman Avatar asked Jun 06 '14 05:06

Gil Birman


People also ask

How does directive work in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What is not recommended in AngularJS?

It is tempting to do too much work in the AngularJS controller. After all, the controller is where the view first has access to JavaScript via $scope functions. However, doing this will cause you to miss out on code sharing across the site and is not recommended by AngularJS documentation.

Can we use multiple directives in AngularJS?

... is quite illustrative as AngularJS doesn't allow multiple directives (on the same DOM level) to create their own isolate scopes. According to the documentation, this restriction is imposed in order to prevent collision or unsupported configuration of the $scope objects.

Which of the following is not an AngularJS directive?

ng-state is not an AngularJS directive. Q 15 - Which of the following is true about ng-app directive? A - ng-app directive defines and links an AngularJS application to HTML.


1 Answers

You should directly define controller function to expose directive API to other directives:

app.directive('menu', function () {
  return {
    restrict: 'E',
    require: '?^menu',
    controller: function($scope){  },
    link: function(scope, element, attrs, ctrl) {
      console.log('ctrl: ', ctrl);

      if (ctrl) {
        element.addClass('nested');
      } else {
        element.addClass('notnested');
      }
    }
  };
}); 

See http://plnkr.co/edit/cKFuS1lET56VOOYD5rrd?p=preview

like image 50
dubadub Avatar answered Oct 19 '22 02:10

dubadub