0

I am new to angular, and have to work with angularjs, also. The majority I can relate to angular, but there is the following code that has me a bit baffled, and any assistance is appreciated.

angular
        .module('Test')
        .directive('nbTest', [savedTest]);

    /* @ngInject */
    function savedTest() {
        var directive = {
            restrict: 'E',

            scope: true,
            templateUrl: 'test/newTest/directives/savedTest/nbSavedTests.tmpl.html',
            controllerAs: 'vm',
            controller: ['$scope', '$mdUtil', '$mdDialog', '$timeout', 'nbApplicationFactory', 'dateService', savedTestCtrl]
        };
        return directive;

What I am specifically confused about is the array for the 'controller'. What I am wanting to do is use the $onInit life cycle hook, but am baffled how to when the controller is defined how it is.

4

2 Answers 2

1

This is how DI is done in AngularJS. To implement $onInit life cycle hook you just need to implement it inside of the controller function like:

function savedTestCtrl($scope, $mdUtil, $mdDialog, $timeout, nbApplicationFactory, dateService) {
    var ctrl = this;
    ctrl.$onInit = onInit;

    function onInit() {
        //your code here
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Following the sequence of your questions.

First, the array literal in the 'controller' property has the purpose of inject dependencies in the controller. The behaviour of your controller is defined in the savedTestCtrl function, the last element of the array. The dependencies defined in the array are injected by the framework, so you can get the dependencies inside your controller with params. The controller must have the same number of params defined in the array. For example, your savedTestCtrl function must have the following definition:

function savedTestCtrl($scope, $mdUtil, $mdDialog, $timeout, nbApplicationFactory, dateService){

  console.log(dateService.text); //prints the property text of your dateService object

}

Second, the $onInit lifecycle hook need to be defined with a function as a property of the controller. Like this:

function savedTestCtrl($scope, $mdUtil, $mdDialog, $timeout,nbApplicationFactory, dateService){

  var vm = this; 
  vm.$onInit = function(){
    console.info('The init of savedTestCtrl')
  } 

}

Because this lifecycle hook is available starting from angular 1.5, make sure that you are using this version or above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.