将用户对象传递给组件模式

时间:2016-12-01 08:01:53

标签: javascript angularjs ecmascript-6 web-component

我有一个可以邮寄的用户列表。此外,我还有一个组件模式窗口,其中包含消息的表单,即每个用户项目都有自己的按钮来切换表单以邮寄给他。我无法弄清楚如何将每个模态实例绑定到调用其范围的用户。这是代码:

用户-list.html

<div ng-repeat="user in $ctrl.users">
    <p ng-bind="user.fullName"></p>
    <button ng-click="$ctrl.openModal(user)"></button>
</div>

用户-list.js

class UserListCtrl {
  constructor(users, $uibModal) {
    'ngInject';
    // an array of users that I get from my service and server
    this.users = users;
    // angular-ui-bootstrap modal window
    this._$uibModal = $uibModal;
    this.animationsEnabled = true;
  }

  openModal(user) {
    let modalInstance = this._$uibModal.open({
      animation: this.animationsEnabled,
      component: 'messageComponent',
      resolve: function () {
        //when I call the modal instance, it logs me user data
        console.log(user);
        return user;
      }
    });
  }
}

消息component.js

let messageComponent = {
  bindings: {
    resolve: '<',
    close: '&',
    dismiss: '&'
  },
  // I bundle the app with webpack, so required templates compile
  template: require('./message.html'),
  controller: function () {
    let $ctrl = this;

    $ctrl.onInit = function () {
      $ctrl.user = $ctrl.resolve.user;
    },

    $ctrl.ok = function () {
      // a log to see if there's user in this instance
      // returns me undefined
      console.log($ctrl.user);
      $ctrl.close({$value: $ctrl.user});
    }

    $ctrl.cancel = function () {
      $ctrl.dismiss({$value: 'cancel'});
    }
  }
};

这是我的组件的模板:

<div class="modal-header">
  <h3 class="modal-title">Send a message to {{$ctrl.user.fullName}}!</h3>
</div>
<div class="modal-body">
   <form>
     <!-- Here goes the form -->
   </form>
</div>
<div class="modal-footer">
   <button type="submit" ng-click="$ctrl.ok">Ok</button>
   <button type="submit" ng-click="$ctrl.cancel">Cancel</button>
</div>

但是对用户的绑定似乎不起作用,因为用户的全名不会显示在我的模态标题中,但是没有异常上升。试图调用应该传递给模态实例的用户总是返回undefined,我试图在我的组件中到处console.log()。我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

错误非常简单。我应该编写onInit()而不是$onInit()方法,这是angular-ui-bootstrap库中的方法。