2017-08-03 78 views
0

控制器構造我使用angular ui router,我需要注入$scope和一些預取的數據爲我controller`s構造。

我能夠實現這一點,當我只將約定添加到解析對象,只要我將$scope服務添加到注射器列表角度ui路由器無法解析路線。

工作打字稿代碼:

$stateProvider.state('parent.child', { 
    url: '/child', 
    template: 'I am the child state', 
    controller: 'TestController', 
    controllerAs: 'vm', 
    resolve: {     
     viewModel:initializeControllerViewModel 
    } 
}); 

initializeControllerViewModel.$inject = [ 
    '$stateParams', 
    '$q', 
    '$timeout' 
]; 

function initializeControllerViewModel(
    $stateParams: ng.ui.IStateParamsService, 
    $q: ng.IQService, 
    $timeout:ng.ITimeoutService) 
{ 
    let deferred = $q.defer(); 

    $timeout(() => 
    { 
     deferred.resolve({ 
      property1: 'foo' 
     }); 
    }, 500); 

    return deferred.promise;  
} 

class TestController 
{ 
    constructor(
     viewModel: any) 
    {    
     //viewModel should be {property1: 'foo'} 
    } 
} 

不工作代碼:

$stateProvider.state('parent.child', { 
    url: '/child', 
    template: 'I am the child state', 
    controller: 'TestController', 
    controllerAs: 'vm', 
    resolve: { 
     '$scope': '$scope', 
     viewModel:initializeControllerViewModel 
    } 
}); 

class TestController 
{ 
    constructor(
     $scope: ng.IScope, 
     viewModel: any) 
    { 
     //$scope should be injected 
     //viewModel should be {property1: 'foo'} 
    } 
} 

回答

0

取下UI路由器範圍並嘗試使用$你們班注入性

class TestController 
{ 
public static $inject = ['$scope', 'viewModel']; 
constructor(
     $scope: ng.IScope, 
     viewModel: any) 
    { 
     //$scope should be injected 
     //viewModel should be {property1: 'foo'} 
    } 
} 
+0

我已經試過了之前,然後'$ scope'變量被正確注入,但'viewModel'的值爲'undefined' –

+0

您是否將'viewModel'添加到$ inject? – Vitalii

+0

不,我沒有,添加它解決了問題,請然後更新您的答案,我會接受它 –

相關問題