[英]Angular Directive in ng-repeat get current clicked item $scope
I have created a directive with a date picker inside of it called calendar. 我创建了一个带有日期选择器的指令,称为日历。 The actual date picker javascript has been created in JQuery and for me to be able to set the ng-model I have found the following code which works:
实际的日期选择器javascript已经在JQuery中创建,对于我来说,能够设置ng-model,我发现以下代码可以正常工作:
var clickedID = "#" + $scope.indexid + "_datePicker";
$(clickedID).trigger('input');
The problem is $scope.indexid is always showing as the last value in the array of calendar directives. 问题是$ scope.indexid始终显示为日历指令数组中的最后一个值。
To clarify for example the directive shows my variables as the following: 举例来说,该指令将我的变量显示如下:
[
{ indexid: 1},
{ indexid: 2},
{ indexid: 3}
]
When any the calendar is clicked on in the page $scope.indexid will always return 3 (the last item in the array). 当在页面上单击任何日历时,$ scope.indexid将始终返回3(数组中的最后一项)。 How would I fix this problem?
我该如何解决这个问题?
It is a very difficult problem to explain. 这是一个很难解释的问题。 If you would like any more information please let me know.
如果您需要更多信息,请告诉我。 I will try to add as much as requested.
我将尝试按要求添加尽可能多的内容。
EDIT more code: 编辑更多代码:
//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}}"/>
When you loop over the array that you need to pass in each object by reference to be able to set values on it. 当您遍历数组时,需要通过引用传递每个对象才能在其上设置值。 You do this like this:
您可以这样操作:
<div ng-repeat="item in items">
<calendar item="item"></calendar>
</div>
item
will hold the current element in the array, so your index has to be called off of that. item
将保留数组中的当前元素,因此必须从该索引中调用它。
In your directive, you can set it up like this: 在您的指令中,可以这样设置:
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
}
This pattern should give you better access to each array item. 这种模式应该使您可以更好地访问每个数组项。 By passing it in by reference you can write back to it;
通过引用传递它,您可以写回它。 changes made to
item
inside the directive will be seen in the items
array on the outer scope. 对指令内部的
item
所做的更改将在外部范围的items
数组中看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.