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的背景色。
非常感谢,这是我在找什么。但记住,我仍然有一个问题,即每当我们的作用域更改时,编译函数运行一次,链接函数函数就会运行。可能是我错了,但我不清楚为什么我们需要在这里添加手表。根据我的理解,链接函数应该自动调用作为我的范围更新..请说明我。 –
你的理解是不正确的。链接功能在模板被克隆后执行一次。它不会在每次范围更改时都执行。 –
谢谢@JBNizet。非常感谢。我将再次学习编译和链接功能。再次感谢您宝贵的时间和宝贵的反馈意见... –