1

What I want to achive? When addComment sends info to profile I want comment box to update (add new comment - works fine!) and scroll down to show new comment (scroll doesn't work).

My idea for solving problem: Set up a lifecycle hook that listen for changes, namely $onChanges. When that occures fire well known scroll function.

All works when I change comments in profile component but when change comes from child component (addComment) nothing happens and $onChanges doesn't trigger even though the change is visible in the view (comment is added).

Part of components tree: components tree

Code:

Parent Component - profile (responsible for logic - component controller)

angular.module('myApp')
      .component('profile', {
        templateUrl: 'views/profile.html',
        controller: function (fetchData) {
          var vm = this;

          //Adds new comment to person object
          function addcomment(author, text){
            console.log('Pushed');
            var d = new Date(),
                avatar = author.toLowerCase().split(" ").join("");
            this.person.comments.push({
              author: author,
              avatar: 'images/' + avatar + '.jpg',
              creationDate: d.getTime().toString(),
              text: text
            });
          }

          this.addcomment = addcomment;
          fetchData.then(function(data) {
            vm.person = data[0];
          });
        }
    });

Child#1 component - addComment (Responsible for sending data(new comment) to parent controller)

angular.module('myApp')
    .component('addComment', {
      templateUrl: 'views/addComment.html',
      bindings: {
        onAddComment: '&'
      },
      controller: function(){
        this.text = "";
        this.author = "Test";
      }
    });

Child#2 component - commentBox (responsible for displaying comments in a box)

angular.module('myApp')
    .component('commentBox', {
      templateUrl: 'views/commentBox.html',
      bindings: {
        comments: '<',
        commentCount: '<'
      },
      controller: function() {
        this.$onChanges = function (changesObj) {
          //place to triger scroll function
          console.log('Changed');
          if (changesObj) {
            console.log('changed!');
          }
        };
      }
    });
eso32
  • 45
  • 5
  • Try broadcasting and listening on rootScope. Just remeber to cleanup the rootScope listener during controller unloading: ` $scope.$on('$destroy', function() { cleanup(); // var cleanup = $rootScope.$on('...',etc..); });` – johan Sep 14 '17 at 09:39
  • Could you update this fiddle to reproduce your problem? http://jsfiddle.net/bgmhqdwg/ Please add your template, etc. – lin Sep 14 '17 at 09:39
  • jsfiddle updated – eso32 Sep 14 '17 at 10:42
  • http://jsfiddle.net/eso32/2gjjsr8n/ – eso32 Sep 14 '17 at 11:09

0 Answers0