【发布时间】:2013-12-11 10:02:21
【问题描述】:
我正在使用 AngularJS 大约一个星期,但我遇到了一个我无法理解的自定义指令问题。 我的主要目标是在带有 $http 服务的控制器中加载 json 数据的指令中创建一个 html 表。
我有一个视图模板。如果我使用 Angular 指令(如 ng-repeat 或表达式),似乎数据已正确加载并绑定到范围,我可以呈现我的视图。
但是如果我在文档根目录使用自定义指令,它会在控制器发送请求之前被触发。所以当我在链接函数中使用范围时,scope.myData 是未定义的。 但是,如果我在 ng-repeat 中使用自定义指令,我可以访问本地范围。我不明白为什么 Angular 指令会在数据加载后触发,以及为什么我之前会触发。我错过了什么吗?
实际上,我的数据确实比示例更复杂,我必须在自定义指令中分析它们以生成我的 html 表:为示例数据中的某些属性(如组名)制作 rowspan 或 colspan。
任何帮助都会很有用,非常感谢。
这是我的示例代码。
app.js
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/test', {templateUrl: 'partials/test.html', controller: 'TestCtrl'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
controllers.js
angular.module('myApp.controllers', []).
controller('TestCtrl',['$scope', '$http',function($scope, $http){
$http.get('data/test.json').success(function(data) {
$scope.myData = data;
});
}]) ;
test.html
<!-- this works perfectly -->
<h3>{{myData.title}}</h3>
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th ng-repeat="col in myData.cols">{{col.title}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in myData.rows">
<td>{{row.group}}</td>
<td ng-repeat="col in row.cols">{{col}}</td>
</tr>
</tbody>
</table>
<!-- does not work ! -->
<table test-table></table>
directives.js
angular.module('myApp.directives', []).
.directive('testTable', ['$compile', function(compile){
return{
link: function(scope,elm,attrs,ctrl){
for(var i = 0, l= scope.myData.rows.length; i<l; i++){
var tr = angular.element(['<tr>', '</tr>'].join(''));
console.log(tr);
for(var j = 0; j<scope.myData.cols.length; j++){
var td = angular.element(['<td>', String(scope.myData.rows[i].cols[j]), '</td>'].join(''));
tr.append(td);
}
elm.append(tr);
}
compile(elm.contents())(scope);
}
}
}]);
test.json
{
"title" : "This is a simple sample data.",
"cols" : [{"title":"Group Name"},{"title":"Col1"},{"title":"Col2"},{"title":"Col3"}],
"rows" : [
{"group" : "group A","cols":["Something","Something else","Other stuff"]},
{"group" : "group A","cols":["Something","Something else","Other stuff"]},
{"group" : "group A","cols":["Something","Something else","Other stuff"]},
{"group" : "group B","cols":["Something","Something else","Other stuff"]},
{"group" : "group B","cols":["Something","Something else","Other stuff"]}
]
}
【问题讨论】:
标签: javascript ajax json angularjs