【问题标题】:data-binding in link() of directive is not working properly?指令的链接()中的数据绑定无法正常工作?
【发布时间】:2015-12-17 12:19:29
【问题描述】:

我在Jsfiddle 进行了 angularjs 示例的演示。 我只是在创建一个 angularjs 指令,它将显示一个背景颜色为红色的 div,其中包含作为模板的数据绑定的静态文本。

var objApp = angular.module("myApp", []);
objApp.controller("myAppController", 
    function($scope) {
       $scope.name2="temp";
    });

objApp.directive("myAppDirective",
    function(){
        return {
           template : "<div style='background-color:red'>"+
                           "Hello {{name}}"+
                           "<div ng-transclude></div>"+
                      "</div>",
           scope : true,
           transclude : true,
           controller : function($scope) {
               $scope.name = "tempController";
           },
           compile : function(tElem, attrs, transcludeFn) {
               return function(scope, iElem, attrs, transcludeFn) {
                   console.log(iElem.html());
                   //iElem.html("<div ng-show='false'>" + 
                   //                  iElem.html() + 
                   //            "</div>");
               }
           }
  });

当注释下一行时,每个绑定都可以正常工作。

iElem.html("<div ng-show='false'>" + iElem.html() + "</div>")

但是一旦评论被删除,绑定就会被破坏。为什么会这样?我必须在 iElem 上设置的新 html 上使用 $compile 吗?当这一行被评论时,它是否已经编译?我一直在寻找答案,但没有一个能帮助我。

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    是的。您需要按如下方式使用 $compile

    $compile('<div ng-show="false">'+iElem.html()+'</div>')($scope, function(cloned, scope){
                    elem.append(cloned); 
    });
    

    编辑:您的问题似乎与这篇文章类似。看看here

    【讨论】:

    • 你能告诉我为什么链接函数需要 $compile() 吗?如果我在指令中使用 compile() 函数,那么一切正常,为什么会这样?你能详细解释一下何时使用 compile 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多