我想在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