Angularjs:为什么在模板中绑定(bind)时自定义指令中的参数没有定义?

标签 angularjs binding scope directive

这是我的测试代码:

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中按钮的标签。它应该有一个默认值,以防没有给出特定值。但似乎无法给出默认值。请问有人知道这是为什么吗?

最佳答案

这是一个有趣的问题 - 问题似乎是 Angular 的摘要周期最终解决 scope.submitText回到未定义。这是我对所发生情况的理论:

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

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

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'
    }
  };
});

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

关于Angularjs:为什么在模板中绑定(bind)时自定义指令中的参数没有定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379186/

相关文章:

javascript - 我的 Angular ng-foreach 绑定(bind)有什么问题?

binding - Knockoutjs 原生模板绑定(bind)和简单的字符串数组

wpf - 绑定(bind)到 DateTime.Now。更新值

c++ - 有没有办法访问隐藏在另一个范围内的局部变量的值?

java - 如何在不创建java对象的情况下从包内的所有类访问方法

javascript - 在 AngularJS 应用程序中加载 JSON(加载谷歌电子表格)

javascript - Jasmine 单元测试的方法称为

angularjs - $destroy 事件在 Angular 不起作用

wpf - 将 DisplayMemberPath 设置为字典的结构值成员

javascript - Javascript "this"运算符如何处理范围?