动态添加ng-bind指令不起作用吗?

时间:2014-05-02 14:18:55

标签: angularjs ng-bind

我通过指令

将属性ng-bind='data'添加到元素中
myApp.directive('myDiv', function() {
    return {
        restrict: 'E',
        link: function($scope, element, attrs) {
            element.html('<div ng-bind="data">me</div>');
}   };  });
function MyCtrl($scope) {
    $('#click').click(function() {
        $scope.data = 'change';
}); }

但是ng-bind没有按预期工作。

http://jsfiddle.net/HB7LU/3427/

3 个答案:

答案 0 :(得分:10)

回答主要问题,您的问题是,如果要在模板中包含绑定,则需要编译元素。其语法如下:

$compile(angular.element("my html"))(scope)

在你的情况下,实际上看起来像是:

myApp.directive('myDiv', function($compile) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            // here adding the ng-bind dynamically
            element.html($compile(angular.element('<div ng-bind="data">me</div>'))(scope));
        }
    };
});

要查看它,请在此处查看更新的小提琴:http://jsfiddle.net/CC8BK/

另一个注意事项是你正在使用jQuery&#34;&#34;点击&#34;事件来更改范围值。使用angular时,您需要首先尝试不使用jQuery,而是使用angular指令。在您的情况下,ng-click是您应该使用的指令。我在你的html中插入了它,这样你就可以看到它的外观。

希望这会让你走上正轨。祝你好运!

答案 1 :(得分:2)

正如@drew_w所说,如果你需要从链接申请,你必须使用$compile编译元素,

或者您可以像

那样使用template
template: '<div ng-bind="data"></div>'

我更喜欢模板

也不要使用像

这样的jquery函数
 $('#click').click(function() {
        $scope.data = 'change';
});

而你可以使用

  $scope.change = function()
    {
        $scope.data = 'change';
    }

ng-click="data = 'change'"  

正如@drew_w所说

查看完整代码

<强> Working demo

<强> HTML

<div ng-controller="MyCtrl">Hello, {{name}}!
    <button id='click' ng-click="change()">click to 'change'</button>
    <my-div>watch, this doesn't change!!!???</my-div>
</div>

<强>脚本

var myApp = angular.module('myApp', []);

myApp.directive('myDiv', function ($compile) {
   return {
            restrict: 'E',
            template:'<div ng-bind="data"></div>'
        };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.data = "me";
    $scope.name = 'Superhero';

    $scope.change = function () {
        $scope.data = 'change';
    }
});

答案 2 :(得分:1)

这是使用Template属性并使用click函数的上述答案的变体:

    myApp.directive('myDiv', function() {

        return {
            restrict: 'E',
            template:'<div ng-bind="data"></div> me'
        };

    });

并在控制器上:

    $scope.click = function() {

            $scope.data = 'change';
        };

并在视图

    <button ng-click="click()">click to 'change'</button>

http://jsfiddle.net/HB7LU/3446/