我已经编写了一个代码,我需要返回mydata的数组值,但是因为我没有for循环,所以即使我在范围内定义了数组值,数组值也是未定义的。 但是,我能够使用{{mydata}}在视图页面上查看该值,但无法在该指令中访问该值。 控制器代码: -
angular.module('myApp.MyController', []);
myApp.controller('MyController', function($scope, $http, API_URL) {
$scope.mydata = [];
$http.get(API_URL).success(function(response) {
var data = response.result;
for (property in data ) {
$scope.mydata.push(data[property]);
}
});
console.log($scope.mydata);
});
指令代码: -
angular.module('myApp.barsChart',[]).
directive('barsChart', function ($parse) {
var directiveDefinitionObject = {
restrict: 'E',
replace: false,
scope: {data: '=chartData'},
link: function (scope, element, attrs) {
var chart = d3.select(element[0]);
chart.append("div").attr("class", "chart")
.selectAll('div')
.data(scope.data).enter().append("div")
.transition().ease("elastic")
.style("width", function(d) { return d + "%"; })
.text(function(d) { return d + "%"; });
}
};
return directiveDefinitionObject;
});
查看页面代码: -
<bars-chart chart-data="mydata"></bars-chart>
<p>{{mydata}} new data is </p>
答案 0 :(得分:0)
angular.module('myApp.MyController', []);
myApp.controller('MyController', function($scope, $http, API_URL) {
$scope.mydata = [];
$http.get(API_URL).success(function(response) {
var data = response.result;
for (property in data ) {
$scope.mydata.push(data[property]);
}
console.log($scope.mydata);
});
});
答案 1 :(得分:0)
你可以使用 $ rootScope变量而不是$ scope 如
myApp.controller('MyController', function($rootScope, $http, API_URL) {
$rootScope.mydata = [];
$http.get(API_URL).success(function(response) {
var data = response.result;
for (property in data ) {
$rootScope.mydata.push(data[property]);
}
});
console.log($rootScope.mydata);
});
您可以访问此变量js文件的任何控制器