Search code examples
angularjsangularjs-service

ng-change function gets run on page load before data loads?


One of my controller functions gets run before my data loads.

The html:

<div ng-show="item.name">
    <input ng-change="doChange()" ng-model="item.name">
</div>

My controller:

$scope.item = { name: 'bob' };
$scope.other = {};

$scope.doChange = function() {
    $scope.item = $scope.other['test'].name
}

// load the data now!
MyService.getData().success(function(newdata) {
    $scope.item = newdata.item;
    $scope.other = newdata.other;
});

My Service:

app.factory("MyService", function($http) {
    return {
        getData: function() {
            return $http.get("/data");
        }
    }
});

This results in

TypeError: Cannot read property 'name' of undefined

because doChange() gets executed before the service has loaded the data. I'm not sure why this happens. Shouldn't doChange only run when the input has changed, yet it's getting run on page load.


Solution

  • Sorry, it turns out elsewhere in the code I had changed item.name which was why it was being launched on page load.

    I had thought ng-model was somehow triggering ng-change on the <input>, but it was me just being foolish.