2017-04-12 64 views
2

我有一個控制器類的組件,它使用綁定對象作爲輸入參數。在構造函數運行後,我可以訪問控制器中的參數。但我無法將其作爲構造函數參數傳遞。解決與控制器類的綁定

製作一個plunker我找到了一個使用$ onInit方法的posible解決方案。 (ui-router doc)

但這是正確的方法嗎?希望這有助於某人,請告訴我它是否可以改進。

這是控制器:

class Controller { 
    constructor(){ 
    'ngInject'; 
    this.$onInit = function(){  // Comment this 
     this.problemScopeHere = angular.copy(this.param); 
    }        // Comment this 
    console.log(this.param);    
    } 
    get(){ 
    this.problemScopeHere = this.param; 
    } 
} 

這裏組件

let Component = { 
    bindings : { 
     param : "=" 
    }, 
    controller : Controller, 
    controllerAs: '$ctrl', 
    templateUrl: 'component.html' 
}; 

let app = angular.module('app', ['ui.router']); 
app.component('comp', Component); 

回答

0

我認爲你應該使用resolve,用你的版本在UI路由器使您可以使用routing to component

.state('app.home' ,{ 
     url: '/home', 
     component: 'comp', 
     bindigns: { 
     param: 'param', 
     }, 
     resolve: { 
     param: function() { 
      return { 
      string: 'I am the object param' 
      } 
     } 
     } 
    }); 

工作小提琴(和你不一樣一點點,因爲我不知道home.html真正需要的,我認爲這僅用於演示目的):https://plnkr.co/edit/jaXQN7YmmkI8AC1DxohI?p=preview。而且,在第一個$onChanges(第一個運行只是在$onInit之前)或$onInit運行之前,您不能使用綁定(從Angular 1.6開始),所以建議在contructor之前不要依賴它們 - 您可以在$onInit中依賴它們,並且我認爲解決方案是最現代化的方式 - 我曾經在template內部傳遞像你這樣的參數,但是從UI Router 1.x中更容易。您可以將$onInit聲明爲常規類方法。而且,您不必使用controllerAs: $ctrl。如果您沒有提供$ctrl作爲默認值 - 我鼓勵您始終使用默認值,以保持所有組件的一致性。

0

你應該只添加PARAM作爲一個屬性到控制器類。