How to get access to a directive attrs with isolat

2019-05-17 21:56发布

问题:

I need to have access to model created by directive and in the same time I need to get attrs in the directive.

JS:

module.directive('createControl', function($compile, $timeout){
 return {            
   scope: {        
     name: '=Name' // Dynamically created ng-model in the directive element
   },
   link: function(scope, element, attrs){
     attrs.$observe('createControl', function(){
       attrs.createControl //is empty if scope is an object, otherwise it is passed from html attribute
     }
   }

HTML:

<div class="control-group" ng-repeat="x in selectedControls">
  <div create-control="{{ x }}"></div>
</div>

If scope is defined as an object, attrs is empty, otherwise it is value passed from html.

What the cause of this behavior? How to get access to a passed attrs and to a models?

回答1:

The problem: create-control needs to evaluate {{x}} within the parent scope, but by making the scope an object when the directive is declared you create an isolate scope. This means that attrs.createControl doesn't have access to x. Therefore, it is empty.

One solution: You can fix this several ways, the best of which is to configure your directive to accept scope.createControl into its isolate scope through an attribute.

Working fiddle: http://jsfiddle.net/pvtpenguin/tABt6/

myApp.directive('createControl', function ($compile, $timeout) {
    return {
        scope: {
            name: '@', // Dynamically created ng-model in the directive element
            createControl: '@'
        },
        link: function (scope, element, attrs) {
            scope.$watch('createControl', function () {
                // the following two statements are equivalent
                console.log(attrs.createControl);
                console.log(scope.createControl);
            })
        }
    }
})


回答2:

Agree with Matt but the following two statements are equivalent only if the attrs is set.

console.log(attrs.createControl);

console.log(scope.createControl);

Otherwise, attrs.createControl will be undefined but scope.createControl will have a function defined.



回答3:

I need to have access to model created by directive

module.directive('createControl', function($compile, $timeout){

    return {            
        ...
        require:'ngModel',
        link:function(scope, element, attrs, ngMdlCntrl){
            //You have the access to the model of your directive here thr. ngMdlCntrl
        }
        ...
    }})

The require ng-model is for the model at you are setting dynamically.