【问题标题】:Angularjs: Why doesn't the parameter in a custom directive is undefined when bind in template?Angularjs:为什么在模板中绑定时自定义指令中的参数未定义?
【发布时间】:2014-10-12 07:17:36
【问题描述】:

这是我的测试代码:

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

myApp.directive("myWidget", function () {
  return {
    restrict: "E",
    scope: {
        submitText: "@"
    },
    template: "<button>{{submitText}}</button>",
    link: function(scope) {
        if(scope.submitText == null){
            scope.submitText = 'Button';
        }    
    }
 };
});

html:

<my-widget></my-widget>
<br>
<my-widget submit-text="TEST"></my-widget>

这里是http://jsfiddle.net/2cAYt/9/的例子

我想将 submitText 定义为 my-widget 中按钮的标签。它应该有一个默认值,以防它没有给出一个特定的值。但似乎无法提供默认值。请问,有人知道为什么吗?

【问题讨论】:

    标签: angularjs binding scope directive


    【解决方案1】:

    这是一个有趣的问题 - 问题似乎是 angular 的摘要周期最终解决了 scope.submitText 回到未定义。这是我的理论:

    • 你设置scope.submitText = 'Button'
    • 由于 @ 是双向数据绑定,因此 Angular 会尝试将新值 'Button' 绑定回属性中的表达式
    • 在您的第一种情况下,没有表达式,因此它尝试将'Button' 绑定到一些未定义的表达式,实际上什么都不做
    • 顺便说一句,即使您尝试在第二种情况下设置scope.submitText(您指定submit-text="TEST"),您也会得到相同的结果,这次尝试将'Button'绑定到一个static表达
    • 在下一个摘要中,未定义的表达式的值仍然是undefined,所以角度将scope.submitText绑定回undefined

    一种可能的解决方案是完全删除属性绑定,例如

    var myApp = angular.module('myApp', []);
    
    myApp.directive("myWidget", function () {
      return {
        restrict: "E",
        scope: {
        },
        template: "<button>{{submitText}}</button>",
        link: function(scope, element, attrs) {
          scope.submitText = attrs.submitText || 'Button'
        }
      };
    });
    

    如果需要,当您的提交文本不是静态时,您仍然可以使用 插值 - &lt;my-widget submit-text="{{interpolation}}"/&gt;。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多