【问题标题】:Why can't I get the attribute value of my custom directive?为什么我无法获取自定义指令的属性值?
【发布时间】:2013-02-19 11:30:59
【问题描述】:

angularjs 代码:

app.directive('test', function(){
  return {
    restrict: 'A',
    scope: {
      myId: '@'
    },
    link: function(scope) {
      alert(scope.myId);
    }
  }
});

你可以看到指令中有一个scope: { myId: '@' }

还有html代码:

<div test my-id='123'></div>

你可以看到我定义了一个my-id='123'

我希望该指令会提醒123,但它会提醒undefined。我的错在哪里?

PS:这是一个现场演示:http://plnkr.co/edit/sL69NqWC70Qfwav5feP2?p=preview

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    您需要$observe 属性(如http://docs.angularjs.org/guide/directive 的“属性”部分所述)来获取插值属性的正确值。

    这是一个有效的 plunk:http://plnkr.co/edit/NtIHmdoO7IAEwE74ifB5?p=preview

    这本质上是angularjs : logging scope property in directive link function displays undefined 的复制品。还应该注意的是,PR https://github.com/angular/angular.js/pull/1555 最近被合并了,你的 plunker 应该在不使用 $observe 的情况下在 AngularJS 的未来版本中工作。

    --

    有问题的演示在最新版本中工作:1.1.3,你可以试试(并将 angularjs url 更改为 1.1.3)。

    【讨论】:

    • 它适用于最新版本:1.1.3,感谢 PrimosK,这真是一个令人困惑的问题 :)
    • 我已经测试了你的 plunk,工作正常。在 Angular 1.2.23 中测试:“未知提供者:iAttrsProvider”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多