Query asked by user
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?
Answer we found from sources
When your view loads, so does its associated controller. Instead of using ng-init
, simply call your init()
method in your controller:
$scope.init = function () {
if ($routeParams.Id) {
//get an existing object
} else {
//create a new object
}
$scope.isSaving = false;
}
...
$scope.init();
Since your controller runs before ng-init
, this also solves your second issue.
As John David Five
mentioned, you might not want to attach this to $scope
in order to make this method private.
var init = function () {
// do something
}
...
init();
If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.
var init = function () {
// do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
if( newVal && newVal.length > 0) {
unwatch();
init();
}
});
Answered By – Mark Rajcok
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0