我遇到了在Angular js中将JSON数据从控制器传递到指令的问题。下面是包含控制器和代码的代码。指令要素:
var app = angular.module('chartApp',[]) ;
app.controller('DataController', ['$scope', function($scope){
$scope.lineData = {
"x": 1,
"y": 5
}, {
"x": 20,
"y": 20
}, {
"x": 40,
"y": 10
}, {
"x": 60,
"y": 40
}, {
"x": 80,
"y": 5
}, {
"x": 100,
"y": 60
}
}]);
app.directive('lineChart',function(){
return{
restrict: 'EA',
scope:{
chartData: '='
},
template: '<ul><li ng-repeat="prop in customer">{{chartData.x}}</li></ul>'
//template:'xValue: {{lineData.x}} yValue: {{lineData.y}}'
} ;
});
下面是代码的html视图部分:
<body>
<div ng-app="chartApp" ng-controller="DataController">
<h1>Pareto Chart</h1>
<div Line-Chart chart-data='lineData' ></div>
</div>
</body>
当我尝试运行上面的代码时,JSON数据没有显示在模板中。它既没有抛出任何错误。对此有任何帮助非常感谢。
答案 0 :(得分:4)
你使用隔离范围,不包含客户因此ng-repeat alwasy什么都不做。
只需将其更改为chartData
,然后将其更改为prop.x
var app = angular.module('chartApp', []);
app.controller('DataController', ['$scope',
function($scope) {
$scope.lineData = [{
"x": 1,
"y": 5
}, {
"x": 20,
"y": 20
}, {
"x": 40,
"y": 10
}, {
"x": 60,
"y": 40
}, {
"x": 80,
"y": 5
}, {
"x": 100,
"y": 60
}];
}
]);
app.directive('lineChart', function() {
return {
restrict: 'EA',
scope: {
chartData: '='
},
template: '<ul><li ng-repeat="prop in chartData">{{prop.x}}</li></ul>'
//template:'xValue: {{lineData.x}} yValue: {{lineData.y}}'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="chartApp" ng-controller="DataController">
<h1>Pareto Chart</h1>
<div Line-Chart chart-data='lineData'></div>
</div>