Reputation: 1648
I would like to live update a div element css property (min-height) in the HTML, if I change a controller variable (the variable contains the height in px, lets say 445).
The problem is, the variable in the directive is always undefined. I tried with $watch also, but still does not work.
Here is a jsfiddle demo: http://jsfiddle.net/xs0upf20/
Here is the sourcecode:
<div ng-app="ctrl">
<div ng-controller="TempCtrl">
<span temp-directive>here we go</span>
</div>
</div>
JS:
angular.module('ctrl', []).controller('TempCtrl', function ($scope, $location, $rootScope) {
$scope.sideheight = 445;
});
angular.module('ctrl').directive('tempDirective', function () {
return {
restrict: 'A',
scope: {
sideheight: '=sideheight'
},
link: function (scope, element, attrs) {
console.log('outside watch');
console.log(scope.sideheight);
element.css('min-height', scope.sideheight+'px');
scope.$watch("onlyvariable", function(newValue,oldValue,scope){
console.log('inside watch');
console.log(scope);
});
}
};
});
The sideheight
variable is initialized with a default value (what I can not access already), and later if I change the variable I would like to see the css property updated.
I also tried '=', '@' binding, still no success. With @ binding, the variable is not even created in scope object, with = char, it has an undefined value. The $parent object does contain the sideheight variable, with the correct 445 value.
Any help is much appreciated.
Upvotes: 1
Views: 440
Reputation: 1546
You need to pass the sideheight from the controller into the directive, like so:
<div ng-app="ctrl">
<div ng-controller="TempCtrl">
<span temp-directive sideheight="sideheight">here we go</span>
</div>
</div>
The directive's scope does not inherit sideheight from the controller, you must tell the directive what property or value on the controller the sideheight property takes.
Upvotes: 3