2017-03-03 15 views
3

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

... 

回答

2

首先檢查這個jsFiddle在這裏你可以看到的結合,爲您的頁面索引四個不同的選項。

檢查你的代碼發佈,我看不出什麼毛病,也許你的問題是在HTML模板

OPTION 1:綁定page變量和增加它的部件

HTML內:

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

CONTROLLER:

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> 

CONTROLLER:

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(); 
     }; 
    } 
} 
+0

尋找你的jsfiddle,看起來你已經來到了,我有同樣的結論? - 這是在子組件中設置新頁面然後使父頁面的功能立即可用的唯一方法是將新頁面號作爲參數傳遞。在你的其他例子中,看起來你實際上正在遞增父代中的頁碼。 –

+0

我同意你的結論。您必須將'$ scope.page'變量傳遞給子組件......可能還有其他方法可以做到這一點,但我認爲這是一個明確的方法。無論如何,如果某些選項無法解決您的問題,告訴我,我可以更新我的jsFiddle或我的答案。 - - 祝你好運 :) –

相關問題