从控制器访问 ngModel 并观察变化
Accessing ngModel from controller and watch for changes
我已经制作了自定义指令,效果很好。它的 plunker 在 http://plnkr.co/edit/GxM78QRwSjTrsX1SCxF7?p=preview
在该指令中有 ngModel 调用 deptStation 我想在控制器中访问它,以便我可以将它用作其他函数的参数来创建新数组。我也想看它,所以我可以调用函数的每一个变化。
<plexus-select items="deptStations" header-text="Select station" text="Select departure..." text-icon="ion-chatbubble-working" text-field="City_Name_EN" text-field2="City_Code" value-field="City_Code" ng-model="deptStation">
</plexus-select>
我尝试编写以下代码,但它不显示控制台日志
$scope.$watch('deptStation', function(newValue, oldValue) {
if(oldValue != newValue) {
// perform something
console.log('New Value ' + newValue);
}
我不太确定 ionic 指令,但你的问题可能是因为一个或多个 ionic 指令创建了一个新的范围,所以只需 ng-model="deptStation"
创建一个新的 属性该范围而不是您的控制器。
为避免这些问题,您应确保不绑定到基元,而是 arrays/objects。您应该像这样创建 属性(为清楚起见重命名为 selectedStation
):
$scope.selectedStation = {value: null};
那么您的手表就可以工作了:
$scope.$watch('selectedStation.value', function (station) {
console.log('watch', station);
});
http://plnkr.co/edit/96VgPzEXZuzxmHt32Afy?p=preview
不过正如@m59 所说,使用双向绑定似乎比使用 ng-model 更好。
我已经制作了自定义指令,效果很好。它的 plunker 在 http://plnkr.co/edit/GxM78QRwSjTrsX1SCxF7?p=preview
在该指令中有 ngModel 调用 deptStation 我想在控制器中访问它,以便我可以将它用作其他函数的参数来创建新数组。我也想看它,所以我可以调用函数的每一个变化。
<plexus-select items="deptStations" header-text="Select station" text="Select departure..." text-icon="ion-chatbubble-working" text-field="City_Name_EN" text-field2="City_Code" value-field="City_Code" ng-model="deptStation">
</plexus-select>
我尝试编写以下代码,但它不显示控制台日志
$scope.$watch('deptStation', function(newValue, oldValue) {
if(oldValue != newValue) {
// perform something
console.log('New Value ' + newValue);
}
我不太确定 ionic 指令,但你的问题可能是因为一个或多个 ionic 指令创建了一个新的范围,所以只需 ng-model="deptStation"
创建一个新的 属性该范围而不是您的控制器。
为避免这些问题,您应确保不绑定到基元,而是 arrays/objects。您应该像这样创建 属性(为清楚起见重命名为 selectedStation
):
$scope.selectedStation = {value: null};
那么您的手表就可以工作了:
$scope.$watch('selectedStation.value', function (station) {
console.log('watch', station);
});
http://plnkr.co/edit/96VgPzEXZuzxmHt32Afy?p=preview
不过正如@m59 所说,使用双向绑定似乎比使用 ng-model 更好。