AngularJS:将表达式绑定到组件

时间:2016-11-20 16:57:13

标签: javascript angularjs components

我有以下组件:

.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 个答案:

答案 0 :(得分: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>