AngularJS : Initializing isolated scope inside a directive -
i have created directive accepts attributes , initializes isolated scope these attributes. if attribute isn't specified, isolated scope should initialized calculated value.
i added link function inspects scope , initializes default values (if no value has been set using attributes). scope has been initialized, if set default value overwritten later framework.
a workaround use $timeout(...) , set afterwards, seems of hack.
function ($timeout) { return { scope: { msg1: '@', msg2: '@' }, template: '<div>{{msg1}} {{msg2}} {{msg3}}</div>', link: function ($scope, $elt, $attr) { var action = function() { if (!$scope.msg2) $scope.msg1 = 'msg1'; if (!$scope.msg2) $scope.msg2 = 'msg2'; if (!$scope.msg3) $scope.msg3 = 'msg3'; }; action(); //$timeout(action, 0); } }; });
i have prepared jsfiddle illustrate happening.
- msg1 initialized via attribute , has correct value @ times.
- msg2 not initialized via attribute, can set using attribute. value overwritten after link method has been called.
- msg3 not initialized via attribute, , isn't possible. value set when constructing controller , works fine.
it seems angularjs creates scope , updates value after controller created , directive linked dom. can tell me recommended way this?
you have operate on attributes if want set defaults '@' type binding. read $compile
you can in compile function:
compile: function(element, attrs) { if (!attrs.msg1) attrs.msg1 = 'msg1'; if (!attrs.msg2) attrs.msg2 = 'msg2'; }
or can use link function 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(); }
the reason there binding attribute setup overrides changes scope variable. need modify attribute value being taken from.
@ or @attr - bind local scope property value of dom attribute. result string since dom attributes strings
Comments
Post a Comment