platypus
platypus

Reputation: 1205

AngularJS ngModelController basic questions

In the Angular documentation in the ngModelController example, the javascript file says:

angular.module('customControl', []).
    directive('contenteditable', function() {
        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel', // get a hold of NgModelController
            ...

Why does "ngModel" refers to the NgModelController? Why isn't it, "require: '?ngModelController" That seems more appropriate from a naming perspective.

Also, what's the difference between using the $setViewValue() function to update the model as opposed to using the $watch() function to watch for changes on the model inside the scope of the directive?

Thanks!

Upvotes: 3

Views: 690

Answers (2)

Manishz90
Manishz90

Reputation: 2624

We can use ngModelController to integrate third-party plug-in with AngularJS app, here the is link to a blog I had written to explain this in detail with example:

Integrate third-party plug-in, with your AngularJS app using ngModelController

Upvotes: 0

rtcherry
rtcherry

Reputation: 4880

Why does "ngModel" refers to the NgModelController? Why isn't it, "require: '?ngModelController" That seems more appropriate from a naming perspective.

Because the require property is used to require a controller directive. For example, the ngModel directive has a controller property that has the $setViewValue and a few other functions. If you are making a custom directive, you can create a controller for it and then other directives can access it by saying require: '?yourDirective' or require: '^yourDirective' or require: 'yourDirective'.

From the Angular documentation:

controller - Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

and

require - Require another controller be passed into current directive linking function. The require takes a name of the directive controller to pass in. If no such controller can be found an error is raised.

You can read more here.

Upvotes: 2

Related Questions