2016-03-04 16 views
1

我想執行初始化函數使用如下綁定屬性時,綁定後加載頁面。如何在使用模塊的angular1.5中綁定後執行函數?

function MyController(){ 
    var my = this; 
    my.init = function(){ 
    if(my.bindproperty == null) 
     //I'd like to set value to my.bindproperty in init function if my.bindproperty is null. 

    } 
} 

bindproperty被綁定在組件中。

var app = angular.module('App'); 
app.component('myDirective', { 
    bindings: { 
    bindproperty: '=' 
    }, 
    controller: MyController, 
    templateUrl: 'path/to/view.html' 
} 

我試圖用ng-init(),但它不能在此刻讀my.bindproperty

HTML如下所示。

<!--in parent directive--> 
<div> 
    <my-directive bindproperty="$ctrl.parentProperty"></my-directive> 
</div> 
+0

您還可以提供使用此功能的HTML代碼片段嗎? –

+0

感謝您的評論。我添加了html代碼片段。 – wtadahiro

回答

1

直接的方法:

function MyController() { 
    var my = this; 

    if(my.bindproperty == null) { 
    // do something; 
    } 
} 

乾淨了一點:

function MyController() { 
    var my = this; 

    (function init() { 
    if(my.bindproperty == null) { 
     // do something; 
    } 
    })(); 
} 

而且,你bindproperty可能是undefined或空字符串,而不是null

您可能想要進行更通用的檢查(例如if (!my.bindproperty))或更具體的檢查(例如my.bindproperty !== 'some valid bind property')。

+0

對不起,我不知道我想做什麼好。如果'my.bindproperty'爲'null',我想將值設置爲'my.bindproperty'。現在它就像你說的那樣是'未定義的'。 – wtadahiro

+0

我還不確定你的意思。檢查null是否無效? –

相關問題