gpt4 book ai didi

javascript - 如何在 AngularJs 模型中使用 $watch?

转载 作者:行者123 更新时间:2023-12-03 08:19:53 26 4
gpt4 key购买 nike

我正在观察模型的变化。如果发生更改,我会调用服务来填充数据。但当页面首次出现时也会调用它。我只想观察用户的选择或取消选择。如何避免在页面加载时观看。另外,当我取消选择时,它会引发下面列出的错误。

ma​​in.html

<div class="col-md-7">
<multiselect-treeview id="epcf" name="epcf" ng-class="{'disabled': PROCESS_EDIT}"
ng-model="nonPersistentProcess.epcfKey" ng-required="true"
o-disable-parents="true" o-max-selectable="1" o-tree-data="epcfTreeData"
placeholder="Select EPCF">
<multiselect-treeview>
<p class="text-danger"ng-show="createProcessFormName.epcf.$dirty && createProcessFormName.epcf.$error.required">
EPCF is required
</p>
</div>

Ctrl.js

$scope.$watch('nonPersistentProcess.epcfKey', function () { 
console.log($scope.nonPersistentProcess.epcfKey);
var item = $scope.nonPersistentProcess.epcfKey[0];
if($scope.nonPersistentProcess.epcfKey) {
TreeHirachyInfo.getEpcfInfo(item.id).then(function (response) {
$scope.epcfObj = response.data;
$scope.processDTO.epcfDescription = $scope.epcfObj.epcfDescription;
$scope.processDTO.epcfToolTip = $scope.epcfObj.epcfToolTip;
});
}
});

错误

TypeError: Cannot read property 'id' of undefined
at Object.fn (Ctrl.js:220)
at Scope.$digest (angular.js:14226)
at Scope.$apply (angular.js:14489)
at angular.js:16215
at completeOutstandingRequest (angular.js:4902)
at angular.js:5282

最佳答案

只需检查您是否有元素:

var item = $scope.nonPersistentProcess.epcfKey[0];
if(item) {
//code goes here...
}

您还可以检查旧值与新值,并仅在它们不同时采取行动:

$scope.$watch('nonPersistentProcess.epcfKey', function (newval, oldval) {
if (oldval == newval) {
//nothing changed, abort:
return;
}
//...code here
}

关于javascript - 如何在 AngularJs 模型中使用 $watch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com