angular.js - Preloading and controller injection of angular-ui-router
ringa_lee
ringa_lee 2017-05-15 17:11:59
0
2
559
After

ui-router's 预加载 resolve obtains data, how to inject it into the controller?

Remarks:

  • In $state, I import the controller file via controllerUrl.

  • My ui-router version is 0.4.2.

Routing code ↓

$stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'views/dashboard/index.html',
    resolve: {
        getList: function ($stateParams, $NetRequest){
            var options = {type: 'charts'};
            
            $NetRequest.post(options).then(function($ref){
                return $ref.data;
            });
        }
    },
    controllerUrl: 'views/dashboard/index',
    controller: 'DashboardController',
    controllerAs: 'vm'
});

Service Code ↓

service.post = function($options){
    var deferred = $q.defer();
    
    // 省略请求函数...
    
    return deferred.promise;
};

If you inject getList directly into the controller at this time, the result will be undefined.

I read the official documentation and there is a $inject parameter, but unfortunately there is no example. I don’t know how to use it.

ringa_lee
ringa_lee

ringa_lee

reply all(2)
仅有的幸福

The problem is solved, the method is actually very simple - -

$stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'views/dashboard/index.html',
    resolve: {
        getList: function ($stateParams, $NetRequest){
            var options = {type: 'charts'};
            
            return $NetRequest.post(options);
            // 因为 $NetRequest.post 已经返回了结果
        }
    },
    controllerUrl: 'views/dashboard/index',
    controller: 'DashboardController',
    controllerAs: 'vm'
});
漂亮男人

'//Get data here'. . . . Did you return your promise?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template