Search code examples
javascriptangularjsecmascript-6web-component

Pass a user object to component modal


I've got a list of users, that can be mailed. Also I've got a component modal window, where the form for message is located, i.e. each user item has its own button to toggle a form to mail him. I can't figure out how to bind each modal instance to user in whose scope it was called. Here's the code:

user-list.html:

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

user-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;
      }
    });
  }
}

message-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'});
    }
  }
};

and here is the template for my component:

<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>

But the binding to user seems not to work, as the user's full name isn't displayed in my modal header, but there's no exceptions risen. Trying to call a user that should be passed to modal instance always returns undefined, I've tried to console.log() it everywhere in my component. How should I do that right way?


Solution

  • The error was terribly simple. Instead of onInit() method I should have written $onInit() which is the method from angular-ui-bootstrap library.