2014-06-22 86 views
0

今天我正在学习指令,我发现编译和链接功能。但我试过我的链接功能不工作。指令不工作的链接功能

我的代码是

<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> 

在这里,我想,如果我在文本框写colorname那么我的指令应该更新,因为文本框被绑定到我的scope.color的背景色。

回答

2

链接功能只被调用一次。如果你想在元素上的背景色为每次设置范围颜色范围的颜色变化,你需要一个手表:

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

工作例如:http://plnkr.co/edit/5IKY9Y4yNHMQ0vzfCR3u?p=preview

或者你可以简单地使用NG式的指令模板,这将自动处理手表:

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

工作例如:http://plnkr.co/edit/uIPkyC5PSCsQZ5T5yELP?p=preview

+0

非常感谢,这是我在找什么。但记住,我仍然有一个问题,即每当我们的作用域更改时,编译函数运行一次,链接函数函数就会运行。可能是我错了,但我不清楚为什么我们需要在这里添加手表。根据我的理解,链接函数应该自动调用作为我的范围更新..请说明我。 –

+0

你的理解是不正确的。链接功能在模板被克隆后执行一次。它不会在每次范围更改时都执行。 –

+0

谢谢@JBNizet。非常感谢。我将再次学习编译和链接功能。再次感谢您宝贵的时间和宝贵的反馈意见... –

相关问题