AngularJS : Initializing isolated scope inside a directive

不问归期 提交于 2019-12-05 11:23:55

You have to operate on the attributes themselves if you want to set defaults for '@' type binding. Read about $compile

You can do it in the compile function:

compile: function(element, attrs) {
    if (!attrs.msg1) attrs.msg1 = 'msg1';
    if (!attrs.msg2) attrs.msg2 = 'msg2';
}

http://jsfiddle.net/5kUQs/9/

OR you can use the link function as well.

link: function ($scope, $elt, attrs) {
    var action = function() {
        console.log('msg1:' + $scope.msg1 + ', msg2:' + $scope.msg2 + ', msg3: ' + $scope.msg3);
        if (!attrs.msg1) attrs.msg1 = 'msg1';
        if (!attrs.msg2) attrs.msg2 = 'msg2';
        if (!attrs.msg3) attrs.msg3 = 'msg3';                
    };
    action();
}

http://jsfiddle.net/5kUQs/13/

The reason for this is that there is a binding with the attribute setup which overrides your changes to that scope variable. We need to modify the attribute that the value is being taken from.

@ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings

You can try initializing your $scope attributes in the controller of the directive, rather than the linking function. When the controller is initialized, the scope should already be set.

I know this is an old one but I came across it looking for an answer and while I didn't get it, I did update your fiddle to get this example working.

function MyController($scope){
 var c = this;
 c.msg1 = $scope.msg1;
 c.msg2 = $scope.msg2;

 var action = function() {
   console.log('msg1:' + $scope.msg1 + ', msg2:' + $scope.msg2 + ', msg3: ' + $scope.msg3);
   if (!c.msg2) c.msg1 = 'msg1';
   if (!c.msg2) c.msg2 = 'msg2';
   if (!c.msg3) c.msg3 = 'msg3';                
 };

 action();

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