【问题标题】:AngularJs directive compile function and isolated scopeAngularJs 指令编译函数和隔离范围
【发布时间】:2016-06-11 14:22:37
【问题描述】:

下面的 plnkr 演示了我的问题

Plnkr

  <ntimes repeat=10 >
      <h1>Hello World - 10 {{smsg}}</h1>
      <h4>More text</h4>
    </ntimes>

指令:

directive('ntimes', function() {
return {
    restrict: 'E',
    scope:{
      smsg: '='
    },
    compile: function(tElement, attrs) {
        var content = tElement.children();
        for (var i = 0; i < attrs.repeat - 1; i++) {
            tElement.append(content.clone());
        }
        tElement.replaceWith(tElement.children());

        return function(scope,elem,attr){
          scope.smsg='abc';
        }
    }
}
})

我有一个编译函数返回链接函数,并且指令范围是隔离的。当我在链接函数中更新范围变量时,页面没有呈现更新的值。我期待看到 abc 而不是 xyz。

请帮忙

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用双向数据绑定时,您必须确保变量连接正确。

    这意味着在您的指令中声明 smsg 范围变量将与将在 DOM 中声明的其他内容进行双向数据绑定。

    现在查看 DOM,缺少此“链接”,这会为您提供此错误。要修复它,您必须将 html 更改为 &lt;ntimes smsg="smsg" repeat=10 &gt;

    当你这样做时,你的新短信将等于'abc'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      相关资源
      最近更新 更多