Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bindToController with require in Angular Directive

If my directive uses "require" to use a different directive, say ngModel, and uses isolate scope how am I able to use the bindToController syntax and still be able to access the injectables (ngModelController) from the controller?

like image 265
silintzir Avatar asked Jan 12 '15 14:01

silintzir


People also ask

What is BindToController in AngularJS?

Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.

What is require in AngularJS?

The ng-required Directive in AngularJS is used to specify the required attribute of an HTML element. The input field in the form is required only if the expression inside the ng-required directive returns true.

Which directive is used for data binding in AngularJS?

A - ng-bind directive binds the AngularJS Application data to HTML tags.

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.


Video Answer


1 Answers

How would you do this without bindToController? All that bindToController: true does is it binds the isolate scope property scope: { prop: "=" } to the property of the controller: this.prop.

In both cases, the way to pass a "required" controller would be the same, which is to require your own controller and set its property to whatever you want, including other controllers:

app.directive("foo", function(){
  return {
    require: ["foo", "bar"],
    controller: function(){
      this.doSomethingWithBar = function(){
        this.bar.doSomething();
      };
    },
    controllerAs: "ctrl",
    bindToController: true,
    link: function(scope, element, attrs, ctrls){
      var foo = ctrls[0], bar = ctrls[1];
      foo.bar = bar;
    }
  }
});
like image 59
New Dev Avatar answered Oct 29 '22 05:10

New Dev