我只是想构建一个可以访问现有json数据数组的指令。表格显示,但有人可以告诉我如何让数据仍然显示在表格中。不知道如何访问它。
var myApp = angular.module('myApp', []);
myApp.controller('countryController', ['$scope',function($scope) {
var countries = [{
"code": "AD",
"name": "Andorra",
"population": "84000"
}, {
"code": "AE",
"name": "United Arab Emirates",
"population": "4975593"
}, {
"code": "AF",
"name": "Afghanistan",
"population": "29121286"
}, {
"code": "AG",
"name": "Antigua and Barbuda",
"population": "86754"
}, {
"code": "AI",
"name": "Anguilla",
"population": "13254"
}, {
"code": "AL",
"name": "Albania",
"population": "2986952"
}
]
$scope.countries = countries;
console.log(countries);
}
]);
myApp.directive('countryLoop', function() {
return {
restrict: 'E',
scope: {
code: '@',
name: '@',
population:'@'
//countries:'&'
},
template: '<table border="2" cellpadding="5" cellspacing="10"><tr><td>Country</td><td>Code</td><td>Population</td></tr><tr ng-repeat="country in countries"><td>{{country.name}}</td><td>{{country.code}}</td><td>{{country.population}}</td></tr></table>',
link: function($scope, element) {
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-App="myApp">
<div ng-controller="countryController">
<table border="2" cellpadding="5" cellspacing="10">
<tr>
<td>Country</td>
<td>Code</td>
<td>Population</td>
</tr>
<tr ng-repeat="country in countries">
<td>{{country.name}}</td>
<td>{{country.code}}</td>
<td>{{country.population}}</td>
</tr>
</table>
</div>
<br>
<country-loop></country-loop>
</body>
答案 0 :(得分:0)
您需要将其与父级绑定:
scope: {
code: '@',
name: '@',
population:'@'
countries:'=' // which is equals to "countries:'=countries'"
}
然后当您使用指令时,您需要指定收集字段:
<country-loop countries="countries"></country-loop>
如果由于某种原因需要以不同方式调用指令属性,您还可以指定要绑定到的属性的名称:
countries:'=data'
将从“data”属性中获取数据,并在指令范围内为“countries”字段分配。
<country-loop data="countries"></country-loop>