我创建了一个指令,其中包含一个名为日历的日期选择器。实际的日期选择器 javascript 已在 JQuery 中创建,为了能够设置 ng-model,我发现以下代码有效:
var clickedID = "#" + $scope.indexid + "_datePicker";
$(clickedID).trigger('input');
问题是 $scope.indexid 始终显示为日历指令数组中的最后一个值。
为了澄清,例如指令显示我的变量如下:
[
{ indexid: 1},
{ indexid: 2},
{ indexid: 3}
]
当在页面中单击任何日历时,$scope.indexid 将始终返回 3(数组中的最后一项)。我该如何解决这个问题?
这是一个很难解释的问题。如果您想了解更多信息,请告诉我。我会尽力添加尽可能多的请求。
编辑更多代码:
//Index Page
<div ng-repeat="item in items">
<calendar indexid="{{$index}}"></calendar>
</div>
//In the Directive
scope: {
ngModel: "=",
indexid: "@"
}
//In Directive Controller
console.log($scope.indexid);
//In the directive template
<input type="text" ng-model="testModel" id="{{::indexid}}"/>
最佳答案
当您循环数组时,您需要通过引用传入每个对象以便能够在其上设置值。你这样做:
<div ng-repeat="item in items">
<calendar item="item"></calendar>
</div>
item
将保存数组中的当前元素,因此必须从中调用您的索引。
在您的指令中,您可以这样设置:
scope: {
item: "=" // reference to 'item' from the parent scope ... your loop
},
template: '<input type="text" ng-model="testModel" id="{{::item.indexid}}"/>',
link: function ($scope) {
console.log($scope.item.indexid);
console.log($scope.testModel); // this is the value of the input
}
此模式应该可以让您更好地访问每个数组项。通过引用传递它,您可以写回它;对指令内的 item
所做的更改将在外部作用域的 items
数组中看到。
关于javascript - ng-repeat 中的 Angular 指令获取当前单击的项目 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33410390/