簡體   English   中英

AngularJS 指令綁定到控制器

[英]AngularJS Directive binding to controller

我試圖找出 AngularJS 指令。 我有以下 JSFiddle 和一個我正在嘗試做的事情的例子。 https://jsfiddle.net/7smor9o4/

正如您在示例中看到的,我希望vm.alsoId變量等於vm.theId 在模板中vm.theId顯示了正確的值,但vm.alsoId沒有。

我究竟做錯了什么? 我怎樣才能實現我的目標。

如果它有幫助,最后的想法是執行以下操作:

function directive(service) {
  var vm = this;
  vm.entity = null;

  init();

  function init() {
    service.getEntity(vm.theId).then(function (entity) {
      vm.entity = entity;
    });
  }
}

Angular 建議您“僅當您想將 API 公開給其他指令時才綁定控制器。否則使用鏈接”。

這是使用鏈接功能的工作小提琴

angular.module('app', [])
  .directive('directive', directive);

angular.element(function() {
  angular.bootstrap(document, ['app']);
});

function directive() {
  return {
    restrict: 'E',
    scope: {
      theId: '<'
    },
    template: `
        alsoId: <span ng-bind="alsoId"></span>
      theId: <span ng-bind="theId"></span>`,
    link: link
  };
}
function link(scope, element, attrs) {

  init();

  function init() {
    scope.alsoId = scope.theId;
  }
}

正如您所注意到的, bindToController綁定在控制器的構造函數中不是立即可用的(與$scope不同,后者是)。 您正在尋找的是 Angular 1.5 引入的一項功能: Lifecycle Hooks ,特別是$onInit

你的想法是對的; 只需按如下方式替換您的init函數定義和調用:

vm.$onInit = function () {
    service.getEntity(vm.theId).then(function (entity) {
      vm.entity = entity;
    });
};

這是您更新的小提琴 (或者,如果沒有此解決方案,您將需要watch 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM