我第一次尝试使用AngularJS自定义指令。
我在使用(或理解...)时遇到了问题。指令的链接函数中的独立作用域。
以下是我的应用程序的这部分代码:
view.html
...
<raw-data id="request-data" title="XML of the request" data="request">See the request</raw-data>
...request是在viewCtrl范围内发布的变量,它包含请求的xml字符串。
rawData.js
directives.directive('rawData', function() {
return {
restrict : 'E',
templateUrl : 'partials/directives/raw-data.html',
replace : true,
transclude : true,
scope : {
id : '@',
title : '@',
data : '='
},
link : function($scope, $elem, $attr) {
console.log($scope.data); //the data is correclty printed
console.log($scope.id); //undefined
}
};
});raw-data.html
<div>
<!-- Button to trigger modal -->
<a href="#{{id}}Modal" role="button" class="btn" data-toggle="modal" ng-transclude></a>
<!-- Modal -->
<div id="{{id}}Modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="{{id}}Modal" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">{{ title }}</h3>
</div>
<div class="modal-body">
<textarea class="input-block-level" rows="10">{{ data }}</textarea>
</div>
<div class="modal-footer">
<!-- <button class="btn" ng-click="toggleTagText('')">{{'cacher'}} l'image</button> -->
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Fermer</button>
</div>
</div>
</div>我不明白为什么当模式弹出时ID是正确显示的,但是当我尝试console.log()它时,它的值是未定义的。
也许我对隔离作用域值(=和@)的理解是错误的。
感谢您的阅读。:)
发布于 2013-06-14 23:13:09
绑定了@的隔离作用域属性在链接函数中不会立即可用。您需要使用$observe
$attr.$observe('id', function(value) {
console.log(value);
});您的模板可以正常工作,因为Angular会自动为您更新隔离范围属性id。当它更新时,您的模板也会自动更新。
如果只是传递字符串,则只需计算一次值,而不是使用@绑定:
link: function($scope, $elem, $attr) {
var id = $attr.id;
var title = $attr.title
console.log(id, title);
}但是,在您的示例中,由于您希望在模板中使用属性,因此应该使用@。
如果您没有使用模板,那么当属性值包含{{}}s -例如title="{{myTitle}}"时,@会很有用。然后,使用$observe的需求就会变得更加明显:每当myTitle的值发生变化时,您的链接函数都可能想要做一些事情。
发布于 2013-06-14 23:14:16
这是故意的,与编译顺序以及“@”和“=”之间的差异有关。
this Google Groups discussion with input from Misko的一些摘录
@ and =做非常不同的事情。一个复制属性值(可以内插),另一个将属性值视为表达式。
@attrs直到后来才被$interpolated,所以它们在链接时不可用。如果你想在link函数中用它们做一些事情,你需要手动$interpolate你自己
发布于 2014-12-29 02:04:37
好吧,上面的答案都没有提到一个关键的方面,即使有'=',在我看来你也不能像下面这样直接访问链接函数内部的作用域。
scope: {
data: '=',
},
link: function(scope, elem, attrs) {
console.debug(scope.data); // undefined但您可以在内部函数中访问作用域,
link: function(scope, elem, attrs) {
scope.saveComment = function() {
console.debug(scope.data);所以在我看来,当scope.data可以使用时可能会有一段时间的滞后。
https://stackoverflow.com/questions/17111016
复制相似问题