我希望能够执行类似于以下简化示例的操作:

class ButtonController {
  set isFoo(value) {
    console.log(value);
    // do something here
  }
}

angular.module('myApp', []).directive('mButton', () => {
  return {
    restrict: 'E',
    replace: true,
    controller: ButtonController,
    controllerAs: 'button',
    template: '<button class="btn" type="button">Blah</button>',
    scope: {},
    bindToController: {
      isFoo: '='
    }
  };
});


并像这样调用指令:

<div ng-app="myApp">
  <m-button is-foo="true"></m-button>
</div>


预览:http://codepen.io/anon/pen/zrWRVr?editors=1010

但是,这会生成一个$compile:nonassign错误,因此要修复,我可以这样做:

<div ng-app="myApp" ng-init="foo=true">
  <m-button is-foo="foo"></m-button>
</div>


预览:http://codepen.io/anon/pen/VexweM?editors=1010

但是我希望能够像前面的标记中那样直接传递布尔值。这不可能吗?如果我想直接传递布尔值,是否真的需要执行以下操作?

class ButtonController {
  set isFooWatcher(value) {
    console.log(value);
    // do something here
  }
}

angular.module('myApp', []).directive('mButton', () => {
  return {
    restrict: 'E',
    replace: true,
    controller: ButtonController,
    controllerAs: 'button',
    template: '<button class="btn" type="button">Blah</button>',
    scope: {},
    bindToController: {
      isFoo: '='
    },
    link(scope, element, attrs, ctrl) {
      scope.$watch(() => ctrl.isFoo, () => {
        ctrl.isFooWatcher = ctrl.isFoo;
      });
    }
  };
});


预览:http://codepen.io/anon/pen/QymxrZ?editors=1010

最佳答案

今天随机发现了这个问题……问题是我有财产的二传手,但没有吸气剂!以下作品:

class ButtonController {
  set isFoo(value) {
    console.log(value);
    this._isFoo = value;
  }

  get isFoo() {
    return this._isFoo;
  }
}

angular.module('myApp', []).directive('mButton', () => {
  return {
    restrict: 'E',
    replace: true,
    controller: ButtonController,
    controllerAs: 'button',
    template: '<button class="btn" type="button">Blah</button>',
    scope: {},
    bindToController: {
      isFoo: '='
    }
  };
});


工作示例:http://codepen.io/anon/pen/rxrZWe?editors=1010

09-20 04:29