2
我有一個指令來從集合中構建動態表。它有兩種類型的列複選框和下拉列表。但是,範圍在指令級別上不能正確解析。他們越來越像'未定義'。另外我需要綁定控制器的下拉選項。角度指令作用域繼承/隔離
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<ui-table source="students">
<check-col title="passed" field="passed"/>
<drop-down-col title="std" field="std" />
</ui-table>
</div>
</div>
角JS
var myApp = angular.module('myApp',[]);
myApp.directive("uiTable", function ($compile) {
var generateTableHtml = function ($scope) {
// header
var html = "<table class='table table-condensed table-bordered table-responsive'><thead class='thead12'><tr class='active'>";
angular.forEach($scope.columns, function (col) {
debugger;
html += "<th scope='col'" +
(col.cssClass ? " class='" + col.cssClass + "'" : "") +
">" + col.title + "</th>";
});
html += "</tr></thead><tbody>";
// body
html += "<tr ng-repeat='item in dataSource'>";
angular.forEach($scope.columns, function (col) {
html += "<td" + (col.cssClass ? " class='" + col.cssClass + "'" : "") + ">";
if (col.type === ColumnType.Check) {
html += "<input type='checkbox' ng-model='item." + col.dataField + "'/>";
} else if (col.type === ColumnType.DropDown) {
html += "<select ng-model='item." +col.dataField + "' ng-options = 'option.Value for option in dataOptions'></select>";
}
html += "</td>";
});
html += "</tr>";
html += "</tbody></table>";
return html;
};
return {
restrict: "E",
replace: true,
transclude: true,
scope: {
dataSource: "=source"
},
controller: function ($scope) {
$scope.columns = [];
this.addColumn = function (col) {
$scope.columns.splice(0, 0, col);
};
},
template: "<div ng-transclude></div>",
compile: function() {
return function ($scope, $elem) {
$elem.html(generateTableHtml($scope));
$compile($elem.contents())($scope);
};
}
};
});
myApp.directive("checkCol", function() {
return {
require: "^uiTable",
restrict: "E",
replace: true,
scope: {
title: "@title",
cssClass: "@class",
dataField: "@field"
},
link: function ($scope, element, attrs, tableControl) {
$scope.type = ColumnType.Check;
tableControl.addColumn($scope);
}
};
});
myApp.directive("dropDownCol", function() {
return {
require: "^uiTable",
restrict: "E",
replace: true,
scope: {
title: "@title",
cssClass: "@class",
dataField: "@field"
},
link: function($scope, element, attrs, tableControl) {
$scope.type = ColumnType.DropDown;
tableControl.addColumn($scope);
}
};
});
//myApp.factory('myService', function() {});
var ColumnType = { Check: 1, DropDown: 2 };
myApp.controller('MyCtrl', function($scope) {
$scope.students = [{id:1, std:10, passed: true}, {id:2, std:9, passed: false}];
$scope.stds= [{Value: 10, Name: '10the std'},{Value: 9, Name: '9the std'},{Value: 8, Name: '8the std'}];
});
而不是添加範圍列列表添加屬性參數,在這個參數中,你有所有傳遞的值tableControl.addColumn(attrs); http://jsfiddle.net/HB7LU/18631/ –
角度版本1.0.1? – sirrocco