AngularJS ng-table插件第二講,下面這個官網例子會根據ng-option來調用map來改變內部數據,然后整個ng-table也會改變。
下面是源碼,我會根據源碼來講解
<div ng-app="myApp">
<div ng-controller="demoController as demo">
<h2 class="page-header">Lazy loading managed array</h2>
<div class="bs-callout bs-callout-info">
<h4>Overview</h4>
<p>You are not limited to having the data array to hand at the time when <code>NgTableParams</code> is created. So for example you could load the data using <code>$http</code> and then hand this to <code>NgTableParams</code></p>
</div>
<div class="form-inline" style="margin-bottom: 20px">
<div class="form-group">
<label for="datasets">Select dataset</label>
<select id="datasets" class="form-control" ng-model="demo.dataset" ng-options="dataset for ds in demo.datasets"
ng-change="demo.changeDs()"></select>
</div>
</div>
<table ng-table="demo.tableParams" class="table table-condensed table-bordered table-striped">
<tr ng-repeat="row in $data">
<td data-title="'Name'" filter="{name: 'text'}" sortable="'name'">{{row.name}}</td>
<td data-title="'Age'" filter="{age: 'number'}" sortable="'age'">{{row.age}}</td>
<td data-title="'Money'" filter="{money: 'number'}" sortable="'money'">{{row.money}}</td>
</tr>
</table>
</div>
</div>
- 使用<code>controller as demo</code>來把<code>controller</code>內的對象綁定在<code>controller </code>的實例對象上。可以跨越<code>scope</code>調用,進行雙向綁定。
- 當<code>ng-option</code>發生變化的時候,會觸發<code>ng-change</code>,<code>ng-change</code>會把值傳進到<code>changeDs()</code>中。
- <code>$data</code>是ng-table內部數據源,<code>row in $data</code> ng-table會遍歷展示數據源。
- <code>filter="{name: 'text'}" </code> filter屬性會規定過濾條件。
(function() {
"use strict";
var app = angular.module("myApp", ["ngTable", "ngTableDemos"]);
app.controller("demoController", demoController);
demoController.$inject = ["NgTableParams", "ngTableSimpleList"];
function demoController(NgTableParams, simpleList) {
var self = this;
self.changeDs = changeDs;//因為已經用controller as demo,相當于實例化controller,直接通過this可以調用
self.datasets = ["1", "2"];//ng-options的值
self.dataset1 = simpleList;//simpleList相當于ngTableSimpleList注入的數據源。與createDs2想對應(當ng-option為1的時候)。
self.dataset2 = createDs2();//與createDs2想對應,與ng-option=2對應與。
self.tableParams = new NgTableParams();//實例化table插件
function changeDs() {//當ng-change時候調用
self.tableParams.settings({
dataset: self["dataset" + self.dataset];//確定調用dataset1還是dataset2
});
}
function createDs2() {//這里就是通過map改變數據
return simpleList.map(function(item) {
return angular.extend({}, item, {
age: item.age + 100
});
});
}
}
})();
(function() {
"use strict";
angular.module("myApp").run(configureDefaults);
configureDefaults.$inject = ["ngTableDefaults"];
function configureDefaults(ngTableDefaults) {//這里可以看出源碼是根據provider實現的
ngTableDefaults.params.count = 5;
ngTableDefaults.settings.counts = [];
}
})();