Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

angularjs - What is the relationship between an Angular 1.X controller and directive

I am NOT asking what the difference between the two is, I'm wondering how they work together when there is both a directive and controller for a component.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure why you got down-voted on this as I think it's a relevant question about one of the less clear aspects of angular 1.x.

exposing directive APIs

One of the prime reasons to set up a directive with a controller is to expose a directive's API to other directives. A good example of this is ngModel and the ngModelController. Many custom directives need access to the ngModel that's also declared on or above where the custom directive is declared. You see this in the directive definition via:

{ require:'^ngModel' }

This is actually saying this custom directive needs to access the APIs available on the ngModelController to do additional work. For instance, you want a directive to do some custom parsing or formatting on a particular ngModel. In my app, I kept getting errors for date strings that came back from the server. I created this custom directive to handle the error and format the string properly (this is coffeescript btw):

.directive 'dateString', [
()->
    {
        priority: 10
        require: 'ngModel'
        link: ($scope, elem, attrs, ngModel)->
            ngModel.$formatters.push (val)-> new Date(val)
    }
]

If there were no ngModelController, I would not have access to the APIs to add a new formatter function.

So in conclusion, we might create directive controllers to provide APIs for other directives that may operate on the same UI element.

classic controller role

In order to be within the spirit and intent of Angular, using a controller to expose APIs to the template is better than trying to use a jquery implementation. In other words, it's better to do this:

directive w. controller

controller: function($scope){ 
    $scope.doSomething = function(){ ... }
},
template: '<div><button ng-click="doSomething()">Click Me</button></div>'

vs something like this

directive w. jquery-like implementation

link: function($scope, elem, attrs){
     elem('button').bind('click', function(){ ... })
},
template: '<div><button>Click Me</button></div>'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...