When I load a view, I'd like to run some initialization code in its associated controller.
To do so, I've used the ng-init directive on the main element of my view:
<div ng-init="init()">
blah
</div>
and in the controller:
$scope.init = function () {
if ($routeParams.Id) {
//get an existing object
});
} else {
//create a new object
}
$scope.isSaving = false;
}
First question: is this the right way to do it?
Next thing, I have a problem with the sequence of events taking place. In the view I have a 'save' button, which uses the ng-disabled
directive as such:
<button ng-click="save()" ng-disabled="isClean()">Save</button>
the isClean()
function is defined in the controller:
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
As you can see, it uses the $scope.isSaving
flag, which was initialized in the init()
function.
PROBLEM: when the view is loaded, the isClean function is called before the init()
function, hence the flag isSaving
is undefined
. What can I do to prevent that?