How to get access to a directive attrs with isolated scope?

给你一囗甜甜゛ 提交于 2019-12-05 18:30:34

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);
            })
        }
    }
})

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.

Rajkamal Subramanian

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!