Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS init variable with ui-router

When I want to init a variable on first start up of a controller I do this in my view

<div ng-controller="testCtrl" ng-init="<%some var from server %>"> <div>

However, I'm now using ui-router like this:

 .state('index', {

            url: "/",
            templateUrl: "/register-form.html",
            controller: "testCtrl"
        })

Because I no longer render the <div ng-controller= etc how to I still init and pass my <%some var from server %> from the template? register-form.html does not have the controller tag anymore because ui-router takes care of it.

like image 284
Prometheus Avatar asked Feb 21 '26 23:02

Prometheus


2 Answers

.state('index', {
    url: "/:id",
    templateUrl: "/register-form.html",
    resolve : {
       id  : function ($http, $stateparams ) {
         var id = '';  
         // resolve id from somewhere, 
         // call to dom hidden field,service/server injection
         return  id; 
       }
    }
    controller: "testCtrl"
});

and a controller :

 .controller('testCtrl', ['id', function(id) {
        //resolved id from state
    }]);

this is another option. if you can't modify url, but want something similar to ng-init. Take a look into resolve function, which takes parameter name id and trying to resolve it, before actual init of controller

hope it will give your some idea.

like image 128
Eugene P. Avatar answered Feb 24 '26 12:02

Eugene P.


Just put it on top of your template:

<div ng-init="<%some var from server %>"> <div>

ngInit doesn't depend on ngController, it just initiates a variable on the scope.

like image 37
Ilan Frumer Avatar answered Feb 24 '26 11:02

Ilan Frumer