2016-11-20 46 views
1

我具有以下組分:AngularJS:bind表達式組分

.component('paging', { 
      templateUrl: "feature/todo-feature/paging/paging.html", 
      controller: "PagingController", 
      bindings: { 
       "data": "<" 
      } 
     }); 

控制器:

$ctrl.incrementPage = function() { 
     if ($ctrl.data[$ctrl.startFrom + $ctrl.limit]) { 
      $ctrl.startFrom = $ctrl.startFrom + $ctrl.limit; 
     } 
    }; 

和視圖:

<paging data="$ctrl.todo.items"></paging> 

我預期$ctrl.todo.items進行評價,並作爲對象從傳遞包裝控制器到PagingController。我的假設是否正確?我究竟做錯了什麼?

+1

'data'被保留作爲一個屬性前綴。爲該綁定使用另一個名稱。 – georgeawg

回答

1

我根據上面的描述創建了一個paging組件,它接受來自包裝控制器(mainController)的數據。請檢查demonstration

我希望這會有所幫助。

分頁組件 -

app.component("paging", { 
    templateUrl: 'pagingComponent.html', 
    bindings: { 
    data: '<' 
    }, 
    controllerAs: 'model', 
    controller: pagingControllerFn 
}); 

function pagingControllerFn() { 
    var model = this; 
    model.currentPage = 0; 
    model.pageSize = 0; 
    model.limit = model.data.length; 

    model.$onInit = function() { 
    model.pageSize = 10; //do intialization 
    }  
    model.$onChanges = function(changes) { 
    model.data = changes; //Called in case of any change in parent controller data 
    }; 

    model.numberOfPages = function() { 
    return Math.ceil(model.limit/model.pageSize); 
    } 
    model.incrementPage = function() { 
    model.currentPage = model.currentPage + 1; 
    } 
    model.decrementPage = function() { 
    model.currentPage = model.currentPage - 1 
    } 
} 

元器件HTML(pagingComponent.html) -

<div> 
    <select ng-model="model.pageSize" id="pageSize" class="form-control"> 
    <option value="5">5</option> 
    <option value="10" ng-selected="true">10</option> 
    <option value="15">15</option> 
    <option value="20">20</option> 
    </select> 
    <ul> 
    <li ng-repeat="item in model.data | startFrom:model.currentPage*model.pageSize | limitTo:model.pageSize"> 
     {{item}} 
    </li> 
    </ul> 
    <button ng-disabled="model.currentPage == 0" ng-click="model.decrementPage()"> 
    Previous 
    </button> 
    {{model.currentPage+1}}/{{model.numberOfPages()}} 
    <button ng-disabled="model.currentPage >= model.limit/model.pageSize - 1" ng-click="model.incrementPage()"> 
    Next 
    </button> 
</div> 

用法 -

<body data-ng-app="myApp" data-ng-controller="mainController as vm"> 
    <paging data="vm.data"></paging> 
</body>