为什么我不能获得自定义指令的属性值?

时间:2022-11-26 22:57:12

The angularjs code:

angularjs代码:

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

You can see there is a scope: { myId: '@' } in the directive.

您可以看到在指令中有一个范围:{myId: '@'}。

And the html code:

和html代码:

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

You can see I defined a my-id='123'.

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

I hope the directive will alert 123, but it alerted undefined. Where is my mistake?

我希望该指令能提醒123,但它警告未定义。我的错误在哪里?

PS: here is a live demo: http://plnkr.co/edit/sL69NqWC70Qfwav5feP2?p=preview

这里有一个实时演示:http://plnkr.co/edit/sl69nqwc70qfwav5fep2?

1 个解决方案

#1


11  

You need to $observe attributes (as described in the "Attributes" section of http://docs.angularjs.org/guide/directive) to get the proper value of interpolated attributes.

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

Here is a working plunk: http://plnkr.co/edit/NtIHmdoO7IAEwE74ifB5?p=preview

这里有一个工作的plunk: http://plnkr.co/edit/ntihmdoo7iaewe74ifb5? p预览。

This is essentially duplicate of the angularjs : logging scope property in directive link function displays undefined. It should be also noted that the PR https://github.com/angular/angular.js/pull/1555 was merged recently and your plunker should work without using $observe in the future versions of AngularJS.

这实质上是angularjs的重复:在指令链接函数中,日志作用域属性显示为未定义。还需要注意的是,最近合并了PR https://github.com/angular/angular.js/pull/pull/1555,在将来的AngularJS版本中,您的柱塞器应该可以在不使用$observe的情况下工作。

--

- - -

The demo in question is worked in latest version: 1.1.3, you can try it (and change the angularjs url to 1.1.3).

这个问题的演示版本是最新版本:1.1.3,您可以尝试一下(并将angularjs url更改为1.1.3)。

#1


11  

You need to $observe attributes (as described in the "Attributes" section of http://docs.angularjs.org/guide/directive) to get the proper value of interpolated attributes.

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

Here is a working plunk: http://plnkr.co/edit/NtIHmdoO7IAEwE74ifB5?p=preview

这里有一个工作的plunk: http://plnkr.co/edit/ntihmdoo7iaewe74ifb5? p预览。

This is essentially duplicate of the angularjs : logging scope property in directive link function displays undefined. It should be also noted that the PR https://github.com/angular/angular.js/pull/1555 was merged recently and your plunker should work without using $observe in the future versions of AngularJS.

这实质上是angularjs的重复:在指令链接函数中,日志作用域属性显示为未定义。还需要注意的是,最近合并了PR https://github.com/angular/angular.js/pull/pull/1555,在将来的AngularJS版本中,您的柱塞器应该可以在不使用$observe的情况下工作。

--

- - -

The demo in question is worked in latest version: 1.1.3, you can try it (and change the angularjs url to 1.1.3).

这个问题的演示版本是最新版本:1.1.3,您可以尝试一下(并将angularjs url更改为1.1.3)。