4
我在理解属性值在AngularJS指令中的工作方式方面有点麻烦。无论我尝试什么,当我尝试在指令控制器中使用它们时,字面属性值都会以undefined
的形式出现。将文字属性值传递给angular js指令
说,在我的HTML我envoke这样的指令:
<div ng-controller="MyCtrl">
<my-directive reference-attr='referenceVal' literal-attr='literalVal'></my-directive>
</div>
referenceVal
和literalVal
在我的控制器都定义是这样的:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.referenceVal = 'This was passed by reference';
$scope.literalVal = 'This was also passed by reference, but should have been literal';
}
我尝试接他们在我的指令:
myApp.directive("myDirective", function() {
return {
restrict: "E",
replace: true,
scope: {
referenceAttr: "=",
literalAttr: "@"
},
template: '<div><p>Reference:{{referenceAttr}}</p><p>Literal:{{literalAttr}}</p></div>',
controller: function ($scope) {
alert("ref: " + $scope.referenceAttr + ", lit: " + $scope.literalAttr);
}
};
});
输出看起来很好:
Reference: This was passed by reference
Literal: literalVal
但警告消息是胡扯:
ref: This was passed by reference, lit: undefined
你可以自己用this JSFiddle
任何想法,为什么literalAttr
在指令范围在这一点上没有定义尝试一下?
古代的Angular版本,如小提琴中使用的1.0.1,有一些插入指令属性的问题(?)。最近的版本显示预期的行为。见[分叉小提琴](http://jsfiddle.net/cD9D2/) –
啊,谢谢Nikos,Angular JS的一个更新版本修正了它(d'oh)。你想让这个答案,我会接受吗? – Dave