I have a directive in angular:
function myDirective() {
return {
scope: {},
restrict: 'A',
link: function($scope, element) {
console.warn("my directive);
}
};
}
angular.module('myapp').directive('myDirective', myDirective);
And I use ng-if
on the html tag that uses the directive.
I want to make the link here run only once. But it does every other time the ng-if is triggered.
I trying passing an argument to the scope
And so use the two way binding to set it to false, like this:
function myDirective() {
return {
scope: {
shouldRun: "="
}
restrict: 'A',
link: function($scope, element) {
$scope.shouldRun = false
console.warn("my directive);
}
};
}
angular.module('myapp').directive('myDirective', myDirective);
And on the element itslef use: <div my-directive shouldRun="true"></div>
But it does not wark.
Could anyone help please?
Thank you!
Edit:
I will try to be more clear: I have a div, with ng-if directive on it. Inside, I have yet another directive. this directive, expands the width of the element on which it is defined. I click a button to trigger the ng-if.
First time - everything works fine.
I click the button again - element is gone.
Another click - element being rendered again.
Only, this time, when the link function is called, it somehow REMEMBERS the previous EXPANDED width.
For example:
<div ng-if="vm.myCondition">
<div my-directive style="width:100px;"></div>
</div>
link: function(scope, elem) {
console.warn($(elem).width());
$(elem).width($(elem).width() * 1.1);
}
first print would be 100; Second time the directive is being created it STARTS by being 110! and that is what I get in the console.
Yes, if I use timeout of 0 - it works fine. But it does not look fine.
See Question&Answers more detail:os