Angular指令控制器——等待属性的赋值/求值

Angular directive controller - wait for assignment/evaluation of attribute

本文关键字:赋值 求值 属性 指令控制器 等待 Angular      更新时间:2023-09-26

假设我有以下标签:

<input name="username" type="text" ng-model="vm.username" available="{{vm.blarg}}">

让我们说blarg被设置为"foo"(从页面的控制器-而不是从下面的指令)。

和我有以下指令:

  angular.module('app')
    .directive('available', RegistrationCtrl);
  function RegistrationCtrl() {
    var directive = {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        ngModel: '=ngModel'
      },
      link: function(scope, element, attrs, ngModel) {
        console.log("link: " + attrs.available); //output: "foo"
      },
      controller: ExampleController,
      controllerAs: 'vm',
      bindToController: true
    };
    return directive;
  }
  function ExampleController($attrs) {
    console.log("controller:" + $attrs.available); //output: "{{vm.blarg}}"
  }

我的问题:是否有任何方法可以使控制器(指令)等待,直到所有属性被angular解析(评估)的那一刻:

{{vm.blarg}} -> "foo"

换句话说,我希望指令只在第一个摘要循环完成后运行。

根据angular文档,最佳实践是:

当你想把一个API暴露给其他指令时,可以使用controller。否则使用link

在你的指令中,如果没有API要暴露,那么不要使用controller。你所有的逻辑都在链接函数中,在这里你可以看到你的作用域属性的变化。