Is it possible to apply multiple AngularJS controllers on the same element

后端 未结 6 1626
悲哀的现实
悲哀的现实 2021-01-31 08:58

Is it possible to apply multiple AngularJS controllers on the same element ?

6条回答
  •  囚心锁ツ
    2021-01-31 09:45

    No, you cannot apply two controllers to the same element, but you can apply multiple directives. And directives can have controllers.

    app.directive('myDirective1', function() {
    return {
    controller: function(scope) {
      //directive controller
      }
     };
    });
    
    app.directive('myDirective2', function() {
    return {
    controller: function(scope) {
      //directive controller
      }
     };
    });
    

    and in the HTML:

    And as mentioned in the comments below, the two controllers could share the same scope, which is often the desired effect; one of the two controller can request a new scope, but you cannot have two new scopes;

    the reason for not allowing two isolated scope on the two directives, is that the view would not know where to get the scope values from, if a scope variable had the same name in the two isolated directive controllers

    Here is an interesting read: Why can't multiple directives ask for an isolated scope on the same element?

提交回复
热议问题