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
1

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Are you sure about order of oldval and newval? I think you got it reversed.
monnef is correct, it's newval before oldval.
True, corrected. Doesn't really matter for this specific example but still... better have it right. :)
Thanks first answer worked!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.