我有一个指令highlight
,我想在指令中使用data-highlight
属性,但我无法在指令中找到它。
HTML:
<li ng-repeat="car in cars" data-highlight="{{car.id}}">
指令:
app.directive('highlight', function() {
function link(scope, element, attrs) {
console.log("highLight directive initialized");
console.log("id=" + attrs.highlight);
var id = 1;
var iw = angular.element(document.querySelector('#iw-' + id));
console.log("iw=" + iw);
}
return {
link: link,
controller: function($scope, $element) {
console.log("highLight directive CONTROLLER initialized");
}
};
})
请看这个plunker:https://plnkr.co/edit/dP2cvut4f5ao5pFe6ka0?p=preview
注意:AngularJs版本是1.0.7
答案 0 :(得分:1)
使用指令范围获取属性值,绑定它们,并使所有内容更明确:
HTML:
<li ng-repeat="car in cars" highlight="car.id">
指令:
app.directive('highlight', function() {
return {
restrict: 'A',
scope: {
highlight:'=',
cars:'='
},
link: function ($scope, $element) {
console.log("highLight directive initialized");
console.log("id=" + $scope.highlight);
var id = 1;
var iw = angular.element(document.querySelector('#iw-' + id));
console.log("iw=" + iw);
}
};
})
答案 1 :(得分:1)
更改您的退货和使用范围
return {
scope: {
highlight: '=datahighlight'
},
link: link,
controller: function($scope, $element) {
console.log("highLight directive CONTROLLER initialized");
}
并更改链接功能
function link(scope, element, attrs) {
console.log("highLight directive initialized");
console.log("id=" + scope.highlight);
var id = 1;
var iw = angular.element(document.querySelector('#iw-' + id));
console.log("iw=" + iw);
}
答案 2 :(得分:1)
在这种情况下,你应该传递car.id
而不用花括号,并通过scope.$eval(attrs.highlight)
获取它:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.cars = [
{ id: 1, price: 100, latitude: 39.65, longitude: 3.0175 },
{ id: 2, price: 200, latitude: 39.67, longitude: 3.0173 }
];
}).directive('highlight', function() {
function link(scope, element, attrs) {
console.log("highLight directive initialized");
var id = scope.$eval(attrs.highlight);
console.log("id=" + id);
var iw = angular.element(document.querySelector('#iw-' + id));
console.log("iw=" + iw);
}
return {
link: link,
controller: function($scope, $element) {
console.log("highLight directive CONTROLLER initialized");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<ul ng-app='app' ng-controller='ctrl'>
<li ng-repeat="car in cars" data-highlight="car.id">
{{car.id}}: {{car.price}} (please, highlight the infoWindow in map onmouseover)
</li>
</ul>