[英]value is not available on the view when creating custom directive in angular js
我正在嘗試創建自定義指令,並在“ ng-repeat”中使用范圍值,除視圖外,其他一切工作正常,我的意思是在視圖(html){{item.value}}上未打印,但正在打印在控制器內的JS代碼(在控制台中)上。
在這方面有什么幫助嗎?
<html ng-app="test">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
</head>
<body ng-controller="test">
<div style="border: 1px solid #000000; height: 30px;width: 100px" ng-repeat="item in items" my-directive on-drag-start="handleDrop(item.id,item.value)"><span style="color:red">{{item.value}} </span></div> //{{item.value}} here value is not printing
</body>
<script>
var app = angular.module('test', []);
app.directive('myDirective', function () {
return {
scope: {
onDragStart: '&'
},
link: function (scope, elem, attrs) {
scope.onDragStart();
}
}
});
app.controller('test', function ($scope) {
console.log("inside the Controller");
$scope.items = [{id: 1, value: "Test1"}, {id: 2, value: "TEst2"}];
$scope.handleDrop = function (elementId, file) {
console.log("Reseult from view", elementId, file);
}
});
</script>
</html>
您可以在指令中創建模板,然后傳遞每個ng-repeat項。 我創建了一個Plunkr 。
首先將HTML中的項目傳遞到指令中
ng-repeat="item in items" my-directive data="item"
然后,您期望指令范圍內的數據
data: '=',
最后是您的模板
template: '<span style="color:red" ng-bind="data.value"> </span>',
對於更復雜的模板和更好的分離,可以使用templateUrl。
問題在於紅色Span內的Scope是指令的范圍,而不是controller / ngRepeat的范圍。 因此,ngRepeat值不會反映在跨度中。 一種方法是將item
分配給另一個屬性item-cache
並將其插入指令范圍:
scope: {
onDragStart: '&',
item: '=itemCache'
}
這樣會將當前項目轉移到指令范圍內,並且您的{{item.value}}
應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.