[英]Angular Directive Attribute - Object Property undefined
我在element指令中定义了一个object属性,它本身是在ng-repeat指令中定义的:
<div ng-repeat="element in array">
<my-directive el-sel="{{element}}>
<something else>
</my-directive>
</div>
这是myDirective:
app.directive('myDirective',function(){
return {
restrict:'E',
scope: false,
link: function($scope,$element,$attrs){
console.log('element:' + JSON.stringify($attrs.elSel));
console.log('href: ' + $attrs.elSel.href);
}
}
});
控制台结果是:
element:"{\"name\":\"a name\",\"href\":\"#something\"}"
href: undefined
有人可以解释这种行为以及我在做什么错吗?
您将{{element}}
作为字符串传递-这就是{{variable}}
所做的。
在短期内,这将解决此问题:
console.log('href: ' + JSON.parse($attrs.elSel).href);
这是将对象传递给指令的最小示例:
var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { $scope.something = { name: 'a name', href: '#somewhere' }; }); app.directive('myDirective', function() { return { restrict: 'E', scope: { elSel: '=' }, link: function($scope, $element, $attrs) { console.log($scope.elSel) } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="MainCtrl"> <my-directive el-sel="something"> </my-directive> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.