AngularJS initialization variable with ui-router

When I want to initialize a variable the first time the controller starts, I do this in my view

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

However, now I use ui-router as follows:

 .state('index', {

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

Because I no longer show <div ng-controller=, etc., how else do I initialize and pass mine <%some var from server %>from the template? register-form.html no longer has a controller tag because ui-router takes care of that.

+3
source share
3 answers

Just put it on top of the template:

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

ngInitindependent of ngController, it simply initiates a variable in the field.

+2
source
.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 controller:

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

. URL-, - ng-init. , id ,

, .

+5

As you want to pass the id, I recommend that you pass the url to $stateParams

.state('index', {
    url: "/:id",
    templateUrl: "/register-form.html",
    controller: "testCtrl"
});

in your controller now

.controller('testCtrl', ['$stateParams', function($stateParams) {
    // cast id to an int since it comes from url now
    var id = +$stateParams.id;
}]);
+1
source

All Articles