指令的链接功能不起作用

时间:2014-06-22 08:02:51

标签: 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 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>

在这里我想如果我在textbox中写colorname然后我的指令的background-color应该更新,因为textbox绑定到我的scope.color。

1 个答案:

答案 0 :(得分: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-style指令,它会自动处理手表:

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

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