等待子组件的绑定更新传播到AngularJS中的父级

时间:2017-03-03 19:37:45

标签: angularjs

是AngularJS的新手。我正在尝试构建一个用于更新当前页面的分页组件。我遇到的问题是当组件对具有双向绑定的值进行更改时。新值不能立即供父母使用。

为了等待绑定值更新,我应该做些什么?或者这是一个模式问题,我应该采取不同的方法来解决问题?

组件 - paging.js

angular.module('someModule')
.component('paging', {
bindings: {
  page:   '=',
  getNextPage: '='  // <- Side note: This is a function, I had problems using the '&' binding
},
controller: function($scope) {
    var $ctrl = this;

    $ctrl.nextPage = function () {
      $ctrl.page++;
      $ctrl.getNextPage();   // <-- Parent will still have the old value for 'page'

      // THIS WOULD WORK, PARENT WOULD HAVE THE UPDATED VALUE FOR 'page'
      // setTimeout(function(){
      //   $ctrl.action();  
      // }, 1000);

      // COULD ALSO PASS THE VALUE THIS WAY
      // $ctrl.action($ctrl.page); 
    }

});

父控制器

...
  $scope.getNextPage = function () {
      $scope.page; // <- This still has the old value 
      ...
  }

...

1 个答案:

答案 0 :(得分:2)

首先,请检查此jsFiddle,您可以在其中看到与页面索引绑定的四种不同选项。

检查您发布的代码,我没有看到任何错误,可能您的问题出现在 HTML模板中。

选项1:绑定page变量并在组件内增加

HTML:

<div ng-controller="parentCtrl">
    <paging page="page"></paging>
</div>

控制器:

function parentCtrl($scope) {
    $scope.page = 1;
}

COMPONENT:

var pagingComponent = {
    bindings: {
        page: '='
    },
    template: '<div><button ng-click="$ctrl.nextPage();">Next Page</button></div>',
    controller: function() {
        var $ctrl = this;

        $ctrl.nextPage = function() {
           $ctrl.page++;
        };
    }
}

选项2:绑定getNextPage()功能形式父控制器

HTML:

<div ng-controller="parentCtrl">
    <paging get-next-page="getNextPage()"></paging>
</div>

控制器:

function parentCtrl($scope) {
    $scope.page = 1;
    $scope.getNextPage = function(page) {
        $scope.page++;
    }
}

COMPONENT:

var pagingComponent = {
    bindings: {
        getNextPage : '&'
    },
    template: '<div><button ng-click="$ctrl.nextPage();">Next Page</button></div',
    controller: function() {
        var $ctrl = this;

        $ctrl.nextPage = function() {
           $ctrl.getNextPage();
        };
    }
}