Angularjs 指令的链接功能不工作
今天我学习指令,因为我发现了编译和链接函数。但我尝试了我的链接功能不起作用 我的代码是Angularjs 指令的链接功能不工作,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,今天我学习指令,因为我发现了编译和链接函数。但我尝试了我的链接功能不起作用 我的代码是 <body ng-app="myModule" ng-controller="myController"> this is directive<br /> <input id="inputTextColor" ng-model="color" type ="text"/>{{color}} <br /> <hello> oldertext old
<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>
这是指令
{{color}}
oldertext oldertext
var myModule=angular.module(“myModule”,[]);
指令(“hello”,函数(){
var指令={};
directive.restrict='E';
directive.template='hi its me';
directive.transclude=true;
directive.compile=函数(元素、属性){
css('border','solid 1px black');
var linkfunction=函数($scope,element,attributes){
css('background-color',$scope.color);
}
返回链接函数;
}
返回指令;
});
控制器(“myController”,函数($scope){
$scope.color=“红色”;
});
这里我想知道,如果我在textbox中写入colorname,那么指令的背景色应该更新,因为textbox绑定到了我的scope.color。链接函数只调用一次。如果希望在每次范围颜色更改时将元素上的背景颜色设置为范围颜色,则需要手表:
var linkfunction = function ($scope, element, attributes) {
$scope.$watch('color', function(newValue) {
element.css('background-color', $scope.color);
});
};
工作示例:
或者您可以简单地在模板中使用ng style指令,该指令将自动处理手表:
directive.template = '<b ng-style="{\'background-color\': color}">hi its me <span ng-transclude></span></b>';
directive.template='hiitsme';
工作示例:非常感谢这就是我要找的。但我仍然有一个问题,编译函数只运行一次,链接函数每次在作用域改变时运行。也许我错了,但我不清楚为什么我们要在这里加手表。根据我的理解链接函数应该自动调用作为我的范围更新..请解释我。你的理解是错误的。克隆模板后,链接函数执行一次。它不会在每次作用域更改时执行。谢谢@JBNizet。谢谢。我将再次学习编译和链接函数。再次感谢您宝贵的时间和宝贵的反馈。。。