我已经使用 Angular 一段时间了。但是,今天我发现我的自定义指令中的 attrs 没有正确绑定很奇怪。以下是代码摘录:
<div ng-repeat="item in items">
<io-map geo-location-x="item.data.x" geo-location-y="item.data.y" zoom-level="item.data.zoom"></io-map>
</div>
angular.directive('io-map', function() {
return {
restrict: 'EA',
scope: {
geoLocationX:'=',
geoLocationY:'=',
zoomLevel:'='
},
template: '<div id="map-' + Math.round(Math.random()*100000000) + '" style="height:400px"></div>',
link: function (scope, element, attrs) {
//Some logic...
//I checked the attrs here, and found attrs.geoLocationX and so on are just plain strings like "item.data.x", meaning they are not bound, while I can assure you that item.data.x has its value.
}
}
})
怎么了?提前谢谢。
将独立作用域与=
绑定一起使用不会使用 attrs
解析属性值。
scope: {
geoLocationX:'=',
geoLocationY:'=',
zoomLevel:'='
},
您应该改用scope
:
link: function (scope, element, attrs) {
//Some logic...
//use
var valueForGeoLocationX = scope.geoLocationX;
}