0

Today I am learning directive in that i found compile and link functions. But I tried my link function is not working.

My code is

<body ng-app="myModule" ng-controller="myController"> this is directive<br /> <input id="inputTextColor" ng-model="color" type ="text"/>{{color}} <br /> <hello> oldertext oldertext </hello> </body> <script> var myModule = angular.module("myModule", []); myModule.directive("hello", function () { var directive = {}; directive.restrict = 'E'; directive.template = '<b>hi its me <span ng-transclude></span></b>'; directive.transclude = true; directive.compile = function (element, attributes) { element.css('border', 'solid 1px black'); var linkfunction = function ($scope, element, attributes) { element.css('background-color', $scope.color); } return linkfunction; } return directive; }); myModule.controller("myController", function ($scope) { $scope.color = "red"; }); </script> 

Here I want if I write colorname in textbox then background-color of my directive should update because textbox is bind to my scope.color.

1 Answer 1

2

The link function is only called once. If you want the background color on the element to be set to the scope color every time the scope color changes, you need a watch:

var linkfunction = function ($scope, element, attributes) { $scope.$watch('color', function(newValue) { element.css('background-color', $scope.color); }); }; 

Working example: http://plnkr.co/edit/5IKY9Y4yNHMQ0vzfCR3u?p=preview

Or you could simply use the ng-style directive in the template, which would deal with watches automatically:

directive.template = '<b ng-style="{\'background-color\': color}">hi its me <span ng-transclude></span></b>'; 

Working example: http://plnkr.co/edit/uIPkyC5PSCsQZ5T5yELP?p=preview

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot this is what i am looking for. But in mind still i am having one question that compile function run one time and link function function run each time whenever our scope changes. May be I was wrong in that but I was not clear exactly why we need to add watch here. According to my understanding link function should call automatically as my scope updatd..Please Explain me.
Your understanding is incorrect. The link function is executed once, after the template has been cloned. It's not executed every time the scope changes.
Thanks @JBNizet . Thanks a lot. I will again learn on compile and link function. And Again Thanks a lot for your valuable time and valuable feedback...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.