Running AngularJS initialization code when view is loaded - angularjs

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?

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.
Fiddle
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();
See jsFiddle
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();
}
});

Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preferred way:
$onInit() - Called on each controller after all the controllers on an
element have been constructed and had their bindings initialized (and
before the pre & post linking functions for the directives on this
element). This is a good place to put initialization code for your
controller.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
//default state
$scope.name = '';
//all your init controller goodness in here
this.$onInit = function () {
$scope.name = 'Superhero';
}
});
Fiddle Demo
An advanced example of using component lifecycle:
The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on bound on $rootScope will not be unbound when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually.
A good place to put that stuff is $onDestroy lifecycle function of an component:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
Fiddle demo

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}

I use the following template in my projects:
angular.module("AppName.moduleName", [])
/**
* #ngdoc controller
* #name AppName.moduleName:ControllerNameController
* #description Describe what the controller is responsible for.
**/
.controller("ControllerNameController", function (dependencies) {
/* type */ $scope.modelName = null;
/* type */ $scope.modelName.modelProperty1 = null;
/* type */ $scope.modelName.modelPropertyX = null;
/* type */ var privateVariable1 = null;
/* type */ var privateVariableX = null;
(function init() {
// load data, init scope, etc.
})();
$scope.modelName.publicFunction1 = function () /* -> type */ {
// ...
};
$scope.modelName.publicFunctionX = function () /* -> type */ {
// ...
};
function privateFunction1() /* -> type */ {
// ...
}
function privateFunctionX() /* -> type */ {
// ...
}
});

Related

AngularJS 1.6.9 controller variable bound to service variable doesn't change

I have 2 components which are both accessing a service. One component delivers an object and the other one is supposed to display it or just receive it. The problem is that after the initialization process is finished the variable in the display component doesn't change.
I have tried using $scope , $scope.$apply(), this.$onChanges aswell as $scope.$watch to keep track of the variable, but it always stays the same.
This controller from the display component provides a text, which is from an input field, in an object.
app.controller("Test2Controller", function ($log, TestService) {
this.click = function () {
let that = this;
TestService.changeText({"text": that.text});
}
});
That is the the service, which gets the objekt and saves it into this.currentText.
app.service("TestService", function ($log) {
this.currentText = {};
this.changeText = function (obj) {
this.currentText = obj;
$log.debug(this.currentText);
};
this.getCurrentText = function () {
return this.currentText;
};
});
This is the controller which is supposed to then display the object, but even fails to update the this.text variable.
app.controller("TestController", function (TestService, $timeout, $log) {
let that = this;
this.$onInit = function () {
this.text = TestService.getCurrentText();
//debugging
this.update();
};
//debugging
this.update = function() {
$timeout(function () {
$log.debug(that.text);
that.update();
}, 1000);
}
//debugging
this.$onChanges = function (obj) {
$log.debug(obj);
}
});
I spent quite some time searching for an answer, but most are related to directives or didn't work in my case, such as one solution to put the object into another object. I figured that I could use $broadcast and $on but I have heard to avoid using it. The angular version I am using is: 1.6.9
I see a problem with your approach. You're trying to share the single reference of an object. You want to share object reference once and want to reflect it wherever it has been used. But as per changeText method, you're setting up new reference to currentText service property which is wrong.
Rather I'd suggest you just use single reference of an object throughout and it will take care of sharing object between multiple controllers.
Service
app.service("TestService", function ($log) {
var currentText = {}; // private variable
// Passing text property explicitly, and changing that property only
this.changeText = function (text) {
currentText.text = text; // updating property, not changing reference of an object
$log.debug(currentText);
};
this.getCurrentText = function () {
return currentText;
};
});
Now from changeText method just pass on text that needs to be changed to, not an new object.

How to call a function from $rootScope

I need to call an Angular function on the hidden event of a bootstrap modal.
Here is my hidden event handler:
$('#modalAddAction').on('hidden.bs.modal',
function (e) {
console.log("in hidden.bs.modal");
var $rootScope = angular.element(document.querySelector("[ng-controller=actionsController]")).scope();
if ($rootScope) {
$rootScope.$apply(function () {
$rootScope.initializeAt1();
});
}
});
Here is the function defined in the controller I need to call:
$scope.initializeAt1 = function () {
$scope.data.addAction.actionTypeId; // initialized in $scope.getActionTypes
$scope.data.addAction.actionStatus = 1;
// initializers help set drop downs to appropriate selection.
$scope.data.addAction.actionType1.actionRecommendedByLerId = 0;
$scope.data.addAction.actionType1.actionsRecommendedByLer = [];
$scope.data.addAction.actionType1.actionProposedBySupervisorId = 0;
$scope.data.addAction.actionType1.actionTakenBySupervisorId = 0;
$scope.data.addAction.actionType1.actionChargeId = 0; // formerly initialized in $scope.getActionCharges
$scope.data.addAction.actionType1.actionCharges = [];
}();
So the first time the controller factory is run, the initializeAt1 function calls itself and does the initialization I need.
Then I try to call initializeAt1 again whenever the modal is hidden, whether from a save buttion, a cancel button, or just clicking on the screen.
The #modalAddAction - hidden event here gives me this error:
[$rootScope:inprog] $digest already in progress
So now I try to change he event handler to this (comment out the apply and just directly call the function from $rootScope):
$('#modalAddAction').on('hidden.bs.modal',
function (e) {
console.log("in hidden.bs.modal");
var $rootScope = angular.element(document.querySelector("[ng-controller=actionsController]")).scope();
//if ($rootScope) {
//$rootScope.$apply(function () {
$rootScope.initializeAt1();
//});
//}
});
And now I get this error.
$rootScope.initializeAt1 is not a function
So I have the rootScope, but why does it not see the function?
I figured it out.
It just didn't like the function being self called after the definition.
When I inspected the $scope off of the $rootScope initailizeAt1 was listed as undefined.
Had to take () off of the end.
And add the call:
$scope.initializeActions = function () {
$scope.initializeAt1();
}
$scope.initializeActions();
at the end.
Will then add init for At2, At3 and so on to initializeActions.

How to store controller functions in a service and call them in AngularJS

I need to execute functions of some controllers when my application ends (e.g. when closing the navigator tab) so I've thought in a service to manage the list of those functions and call them when needed. These functions changes depending on the controllers I have opened.
Here's some code
Controller 1
angular.module('myApp').component('myComponent', {
controller: function ($scope) {
var mc = this;
mc.saveData = function(objectToSave){
...
};
}
});
Controller 2
angular.module('myApp').component('anotherComponent', {
controller: function ($scope) {
var ac = this;
ac.printData = function(objects, priority){
...
};
}
});
How to store those functions (saveData & printData) considering they have different parameters, so when I need it, I can call them (myComponent.saveData & anotherComponent.printData).
The above code is not general controller but the angular1.5+ component with its own controller scope. So the methods saveData and printData can only be accessed in respective component HTML template.
So to utilise the above method anywhere in application, they should be part of some service\factory and that needs to be injected wherever you may required.
You can create service like :
angular.module('FTWApp').service('someService', function() {
this.saveData = function (objectToSave) {
// saveData method code
};
this.printData = function (objects, priority) {
// printData method code
};
});
and inject it wherever you need, like in your component:
controller: function(someService) {
// define method parameter data
someService.saveData(objectToSave);
someService.printData (objects, priority);
}
I managed to make this, creating a service for managing the methods that will be fired.
angular.module('FTWApp').service('myService',function(){
var ac = this;
ac.addMethodForOnClose = addMethodForOnClose;
ac.arrMethods = [];
function addMethodForOnClose(idModule, method){
ac.arrMethods[idModule] = {
id: idModule,
method: method
}
};
function executeMethodsOnClose(){
for(object in ac.arrayMethods){
ac.arrMethods[object].method();
}
});
Then in the controllers, just add the method needed to that array:
myService.addMethodForOnClose(id, vm.methodToLaunchOnClose);
Afterwards, capture the $window.onunload and run myService.executeMethodsOnClose()

$postLink not called in angular 1.5 component

Given the following:
var Panda;
(function (Panda) {
"use strict";
var BulkCaptureComponentController = (function () {
function BulkCaptureComponentController() {
this.textBinding = '';
this.dataBinding = 0;
}
BulkCaptureComponentController.prototype.$onInit = function () {
console.log('init');
};
BulkCaptureComponentController.prototype.$postLink = function () {
alert('1');
};
BulkCaptureComponentController.prototype.add = function () {
this.functionBinding();
};
return BulkCaptureComponentController;
}());
var BulkCaptureController = (function () {
function BulkCaptureController() {
this.value = 0;
}
BulkCaptureController.prototype.$postLink = function () {
alert('1');
};
BulkCaptureController.prototype.$onInit = function () {
console.log('init');
};
BulkCaptureController.prototype.add = function () {
this.value = this.value + 1;
};
return BulkCaptureController;
}());
var BulkCaptureComponent = (function () {
function BulkCaptureComponent() {
this.bindings = {
textBinding: '#',
dataBinding: '<',
functionBinding: '&'
};
this.controller = BulkCaptureComponentController;
this.templateUrl = '/areas/schedule/views/bulkcapture/bulk-capture.html';
}
return BulkCaptureComponent;
}());
Panda.panda.component('bulkCaptureComponent', new BulkCaptureComponent());
Panda.panda.controller("BulkCaptureController", BulkCaptureController);
})(Panda || (Panda = {}));
;
Why is $postLink never called by angular.
My template (for now) just contains html content.
Both init methods work perfectly, but $postLink is not called.
Some new lifecycle hooks (including $postLink) were added in Angular 1.5.3
$onChanges(changesObj) - Called whenever one-way bindings are updated. The changesObj is a hash whose keys
are the names of the bound properties that have changed, and the values are an object of the form
{ currentValue: ..., previousValue: ... }. Use this hook to trigger updates within a component such as
cloning the bound value to prevent accidental mutation of the outer value.
$onDestroy - Called on a controller when its containing scope is destroyed. Use this hook for releasing
external resources, watches and event handlers.
$postLink - Called after this controller's element and its children been linked. Similar to the post-link
function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
Note that child elements that contain templateUrl directives will not have been compiled and linked since
they are waiting for their template to load asynchronously and their own compilation and linking has been
suspended until that occurs.
They are not available in previous 1.5.x versions.

Reusable components in angular controller

I am trying to create a reusable component for my controllers which can be used multiple times in different controllers.
See plunker: http://plnkr.co/edit/Lc4z4L?p=preview
The problem shown in the plunker is, that in the FirstCtrl the same message is shown than in the SecondCtrl.
How can I achieve some kind of isolated scope with the service?
Or am I using the wrong concepts?
While it's true a service only has a single instance, you can also return a function which you can then new in your controller which will give you an individual instance of that function:
app.service('alertService', function($timeout) {
return function () {
// assign this to service only because I'm lazy
var service = this;
var timeout;
// start with empty array holding the alerts.
service.alert_list = [];
// method to add an alert
// alert_obj is a object with members type = ( success | info | warning | danger )
// and msg which is the message string
service.addAlert = function (alert_obj) {
service.alert_list = [];
service.alert_list.push(alert_obj);
$timeout.cancel(timeout);
timeout = $timeout(service.clearAlerts, 5000);
};
service.clearAlerts = function clearAlerts() {
service.alert_list = [];
};
}
});
Your updated controller would now look like this:
app.controller('SecondCtrl', function($scope, alertService, $timeout) {
$scope.alertService = new alertService();
$scope.alertService.addAlert({"type": "info", "msg": "Infomessage II"});
$scope.name = 'World II';
});
Updated plunker: http://plnkr.co/edit/RhJbbxj4XxdwY6GAest9?p=preview

Resources