我想在AngularJS中構建一個指令,該指令有一個可以包含其他AngularJS指令的模板。我所有的指令都需要一個「id」屬性,所以我需要在模板內的指令中設置「id」。但是,不管我怎麼做,AngularJS不斷拋出此錯誤:在AngularJS指令元素上動態設置屬性
Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{field.id}}] starting at [{field.id}}].
http://errors.angularjs.org/1.4.6/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7Bfield.id%7D%7D&p4=%7Bfield.id%7D%7D
at angular.js:68
at Object.AST.throwError (angular.js:13010)
at Object.AST.object (angular.js:12997)
at Object.AST.primary (angular.js:12905)
at Object.AST.unary (angular.js:12893)
at Object.AST.multiplicative (angular.js:12880)
at Object.AST.additive (angular.js:12871)
at Object.AST.relational (angular.js:12862)
at Object.AST.equality (angular.js:12853)
at Object.AST.logicalAND (angular.js:12845)
我知道AngularJS是精做這樣的事情:<div id="{{field.id}}">[...]</div>
。它最終被正確渲染,並將「{{field.id}}」替換爲field.id的實際值。然而,一旦我嘗試將我的指令應用於該div,或者將該指令作爲一個元素使用,AngularJS就會成爲balks。我已經嘗試了所有的以下的所有結果無論是在上面或指令的ID設置爲「field.id」,而不是「field.id」值誤差:
<!-- result in error shown above -->
<mydirective id="{{field.id}}"></mydirective>
<div mydirective id="{{field.id}}"></div>
<div class="mydirective" id="{{field.id}}"></div>
<mydirective ng-attr-id="{{field.id}}"></mydirective>
<div mydirective ng-attr-id="{{field.id}}"></div>
<div class="mydirective" ng-attr-id="{{field.id}}"></div>
<!-- result in id set to "field.id" -->
<mydirective id="field.id"></mydirective>
<div mydirective id="field.id"></div>
<div class="mydirective" id="field.id"></div>
<mydirective ng-attr-id="field.id"></mydirective>
<div mydirective ng-attr-id="field.id"></div>
<div class="mydirective" ng-attr-id="field.id"></div>
在情況下,它可以幫助,與模板指令的總體佈局是這樣的:
<div ng-repeat="field in fields" ng-show="field.visible">
<!-- some other stuff -->
<mydirective ng-if="field.type == 'foobar'" id="{{field.id}}"></mydirective>
<!-- some other stuff -->
</div>
我看到與該指令的另一屬性相同的問題一樣,所以它不是隻限於在「id」屬性。
縮短了指令引發錯誤的版本:
var application = angular.module('application', []);
application = application.directive('mydirective', ['$http', function($http){
return {
restrict: 'AEC',
scope:{
mydirectiveId: '=id',
id : '@',
// a few other attributes
},
templateUrl: 'mydirective.html',
controller: function ($scope, $element){
if($scope.id === undefined){
console.error("The 'id' on mydirective is missing!");
}
// more logic... sorry can't post this
}
};
}]);
當您使用'ID = 「field.id」'你也必須使用' id:'=''。 – zeroflagL