0

I am watching a model for changes. If a change happens, I call a service to populate data. But it is also invoked when the page first. I just want to watch for a user's selection or de-selection. How can I avoid watching on page load. Also, when I de-select, it throws the error listed below.

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;
        });
    }
});

error

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
Glenn
  • 8,932
  • 2
  • 41
  • 54
aftab
  • 693
  • 1
  • 12
  • 27
  • 1
    I think this question has already been answered: http://stackoverflow.com/questions/16947771/how-do-i-ignore-the-initial-load-when-watching-model-changes-in-angularjs – Jakob Nov 18 '15 at 19:22

1 Answers1

1

Just check that you got an item:

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

You can also check the old value vs. new value and act only when they're different:

$scope.$watch('nonPersistentProcess.epcfKey', function (newval, oldval) {
    if (oldval == newval) {
        //nothing changed, abort:
        return;
    }
    //...code here
}
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208