如何将 $watch 用于 AngularJs 模型?

How to use $watch for AngularJs model?

我正在观察模型的变化。如果发生变化,我会调用服务来填充数据。但它也会在页面第一时被调用。我只想观察用户的 selection 或 de-selection。我怎样才能避免在页面加载时观看。此外,当我取消 select 时,它会抛出下面列出的错误。

main.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
}