2

I just want to know what is the best practice for AngularJS if i want to run a function if the user goes to this page.

So for example. i have this url http://localhost:3000/post/58fc0449a467230cb003151d It will show the post with that ID. So the way i show it is, on the page, im using ng-init="function()" so that everytime the user goes to this page it will initialize the function first, which is, that function calls to the backend and returns me the data that i need.

So my question is, is this the best approach/practice on this one? Using ng-init to call the function then show the data to the view?

**UPDATE

Thanks for the answers! By the way im using a controller for this one, my function resides on the controller. i'll paste my code here.. The code here shows the messages by the users retrieved from the database

Messages.htm

<div ng-controller="MessageController as mc" ng-init="messageGet()" class="container" style="height: 90vh">
<h1>Messages</h1>
<div class="row">
    <div class="col-md-12">
        <ul class="media-list" ng-repeat="messages in theMessages">
            <a href="#"> 
                <li class="media card-1">
                    <div class="media-left">
                        <a href="#">
                            <img class="media-object" src="/public/images/matt.jpg" alt="avatar">
                        </a>
                    </div>
                    <div class="media-body">
                        <h5 class="media-heading" ng-if="messages.user1 !== username">{{messages.user1}}</h5>
                        <h5 class="media-heading" ng-if="messages.user2 !== username">{{messages.user2}}</h5>
                        <strong>Topic: </strong>{{messages.postname}}
                        <h5><strong>{{messages.recentmessage.sender}}</strong>: {{messages.recentmessage.message}}  </h5>
                        <div>
                        <a href="/messages/{{messages._id}}" class="btn btn-info" style="margin-bottom: 10px">View message</a>
                        </div>
                    </div>
                </li>
                </a>
        </ul>
    </div>

MessageController

var app = angular.module('main');

app.controller('MessageController', ['$rootScope','MessageService', '$scope', '$localStorage', 'mySocket', '$location', '$stateParams', function($rootScope, MessageService, $scope, $localStorage, mySocket, $location, $stateParams){
   $scope.currentUrl = $location.$$path;   
   var vm = this;

    $scope.messageGet = function(){
        var result = MessageService.getMessages()
            .then(function(result){
                $scope.theMessages = $localStorage.messages;
                $scope.username= $localStorage.username;
            });
    };

MessageService

var app = angular.module('main');

app.service('MessageService', ['$http', '$localStorage', function($http, $localStorage){

    var vm = this;

    vm.getMessages = function(){
        var getmessage = {
            method: 'POST',
            url: '/api/getmessages',
            dataType: 'json',
            contentType: 'application/json',
            data: {
                userid: $localStorage.userid
            }
        };

        return $http(getmessage)
            .then(function(response){
                $localStorage.messages = response.data.info;
                return true;
            });
    };

So as you can see, when i go to the url localhost:3000/messages it will load the Messages.htm template then i will run the function "messageGet()" because i need to get the messages from the database then display it on my view. If i will not use ng-init, then how will i run the function when the user visits this specific url?

2nd Update

So i tried to get rid of the ng-init function, i used an Immediately-Invoked Function

MessageController

(function messageGet (){
    console.log('Messaged run!');
    var result = MessageService.getMessages()
        .then(function(result){
            $scope.theMessages = $localStorage.messages;
            $scope.username= $localStorage.username;
        });
})();

So everytime the Message.htm is loaded, this function is ran.

My question is, will this do? instead of ng-init?

Thank you!

3
  • 1
    'Best practice' is to use router module for that. ng-init is recommended for literally nothing, it just results in lousy code and nothing else. Commented Apr 23, 2017 at 3:12
  • Is the messageGet function part of the controller? Commented Apr 23, 2017 at 11:28
  • yes the messageGet function is inside the MessageController Commented Apr 23, 2017 at 11:54

2 Answers 2

4

As @georgeawg stated you should use the designated controller for this kind of actions.
If you're using angular version >= 1.5 you should use the controller property $onInit for it.
Read more about the angular component and their life cycles here.

If you're using an older version you can do the following:

function MyController() {
     function init() {
     //enter init code here
     }

     init();
}

You can read more about it here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! i updated my question. i uploaded my code, the function that im initializing is residing on the controller.
3

im using ng-init="function()" so that everytime the user goes to this page it will initialize the function first

That use of ng-init is not recommended. Use controllers for that.

From the Docs:

ngInit

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat as seen in [this demo]; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

— AngularJS ngInit Directive API Reference

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.