如何在angular1.5中使用模块绑定后执行函数?

时间:2016-03-04 04:24:37

标签: javascript angularjs binding

我想在绑定后加载页面时使用绑定属性执行初始化函数。

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>

1 个答案:

答案 0 :(得分: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')。