我对ng-init有一个小小的疑问,实际上我有一些图表。
在页面加载上,我没有显示任何内容,但是一旦我第一次单击特定的按钮,那么我的整个图表和表就会显示出http请求接收到的数据。但是之后,如果我单击另一个按钮并执行相同的http请求,那么它将更新趋势线和表,而不是分段。当我测试ng-init =“myFunction(索引)”方法时,将在下面的div中使用ng-init呈现分段,它不会在随后的单击中更新。
<form>
<md-input-container>
<label for="myInput">Search Division</label>
<md-icon md-svg-icon="~/Content/myIcons/searchicon/ic_search_black_36px.svg"></md-icon>
<input type="text" id="myInput" ng-model="searchDiv" md-autofocus>
</md-input-container>
<md-content ng-repeat="prod in listofProd | filter: searchDiv">
<md-button class="md-whiteframe-1dp card" ng-click="generateChart(prod)" flex-sm="100" flex-gt-sm="100" flex-gt-md="100">
{{prod}}
</md-button>
</md-content>
</form>
<div layout="row" layout-wrap>
<div flex="25" style="width:1000px;height:300px; border: 1px solid skyblue;" ng-repeat="year in years track by $index" id="piechart{{$index}}" ng-init="myFunction($index)">
</div>
</div>这是ng函数的angularjs代码。
(function () {
'use strict'
angular.module("GAiiNSApp").controller("ProdPerDash", ['$http', '$scope', '$log', function ($http, $scope, $log) {
$scope.isLoading = false;
$scope.hideme = true;
var currentdate = new Date();
var startdd = "01";
var startmonth = "00";
var lastyear = currentdate.getFullYear() - 3;
var enddd = "31";
var endmonth = "11";
var endyear = currentdate.getFullYear();
$scope.StartDate = new Date(lastyear, startmonth, startdd);
$scope.EndDate = new Date(endyear, endmonth, enddd);
$scope.Region = "Local";
$scope.Country = "";
$scope.ProductLineSelected = false;
$scope.ButtonText = "CUSTOMIZE";
$scope.clicked = false;
$scope.Yes = function () {
if (!$scope.clicked == true) {
$scope.ButtonText = "CANCEL";
$scope.clicked = true;
}
else {
$scope.ButtonText = "CUSTOMIZE";
$scope.clicked = false;
}
}
$scope.alert = function (message) {
$window.alert(message);
}
$scope.Regions = ["Export", "Local"];
$http.get('/General/API/GetProductDivision').then(function (res) {
$scope.listofProd = res.data;
});
$scope.selectedProduct = "";
$scope.generateChart = function (prodname) {
$scope.selectedProduct = prodname;
$scope.isLoading = true;
$http.get('/Marketing/MarketingAPI/ProdPerformance', {
params: {
StartDate: $scope.StartDate,
EndDate: $scope.EndDate,
ProductDivision: prodname,
Division: $scope.Region,
Area: $scope.Country
}
}).then(function (res) {
var resArray = res.data;
var trendarray = [];
$scope.TableRecords = resArray;
$scope.hideme = false;
var json = resArray;
// console.log("Array of Objects: " + JSON.stringify($scope.TableRecords));
var groupedData = {};
var result = [];
resArray.forEach(function (item) {
var year = item.SecuredYear;
var value = item.ValueInDhs;
if (groupedData.hasOwnProperty(year)) {
groupedData[year] += value;
} else {
groupedData[year] = value;
}
});
//Pie chart data starts here
var years = [];
json.forEach(function (obj) {
if (years.indexOf(obj.SecuredYear) == -1)
years.push(obj.SecuredYear);
});
//$scope.years = years;
$scope.years = angular.copy(years);
$scope.pichartsview = true;
$scope.myFunction = function (index) {
var data = [['Product', 'ValueInDhs']];
json.forEach(function (obj) {
if (obj.SecuredYear == years[index]) {
data.push([String(obj.GroupName).trim(), obj.ValueInDhs]);
}
});
$scope.displayChart(data, index);
}
$scope.displayChart = function (dataForChart, index) {
var chartData = dataForChart;
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChartPie);
function drawChartPie() {
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: { left: 10, top: 20, width: "80%", height: "80%" },
legend: 'bottom',
is3D: true,
pieSliceText: 'percentage',
pieSliceTextStyle: {
fontSize: 8
},
title: $scope.selectedProduct + " - " + $scope.years[index]
};
var chart = new google.visualization.PieChart(document.getElementById('piechart' + index));
$scope.$apply(function () {
chart.draw(data, options);
});
}
}
//Pie chart data ends here
for (var year in groupedData) {
var tmp = {};
tmp[year] = groupedData[year];
result.push(tmp);
}
result.forEach(function (obj, index) {
var key = Object.keys(obj)[0];
trendarray.push([parseInt(key, 10), obj[key]]);
});
trendarray.splice(0, 0, [{ label: 'SecuredYear', type: 'number' }, { label: 'ValueInDhs', type: 'number' }]);
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
$scope.isLoading = false;
function drawChart() {
var data = google.visualization.arrayToDataTable(
trendarray
);
var options = {
legend: 'none',
title: 'Product Performance Trendline - ' + $scope.selectedProduct + " - " + $scope.Region,
hAxis: { title: 'Secured Year', format: '0' },
vAxis: { title: 'Secured Value in DHS' },
trendlines: {
0: {
lineWidth: 5,
type: 'polynomial',
visibleInLegend: true,
color: 'green',
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div2'));
chart.draw(data, options);
}
})
$scope.ProductLineSelected = true;
};
}]); //this is ctrl closing
})(); //this is function closing发布于 2016-12-10 14:55:47
由于
Angular 1.2,它有一个选项track by,以防止中继器重新呈现所有的项目,以提高性能。
更多信息可在以下网站找到:http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/
这就是为什么对于已经呈现的相同的years,不会再次触发years,因为您已经使用了track by here ng-repeat="year in years track by $index"。
即使您删除了它,ng-init也不会再次被触发,因为这里的years是一个数组,在这个数组中,Angular非常出色,可以根据其值来跟踪,尽管没有显式的track by。
因此,我们必须将years从简单的数组改为object array,[{year: obj.SecuredYear}],让角产生一个不相同的$$hashKey,当对象每次变化时,转角将通过触发ng-init重画中继器。
所以与此相关的变化是,
<div flex="25" style="width:1000px;height:300px; border: 1px solid skyblue;"
ng-repeat="year in years" id="piechart{{$index}}" ng-init="myFunction($index)">
</div>JS (人口years)
var years = [];
json.forEach(function (obj) {
var exists = years.filter(function(y) {
return y.year === obj.SecuredYear;
});
if (exists.length === 0) { // This will replace the `indexOf` check
years.push({year: obj.SecuredYear}); // change here
}
});
$scope.years = years;JS (myFunction())
$scope.myFunction = function (index) {
var data = [['Product', 'ValueInDhs']];
json.forEach(function (obj) {
if (obj.SecuredYear == years[index].year) { // change here at years[index].year
data.push([String(obj.GroupName).trim(), obj.ValueInDhs]);
}
});
$scope.displayChart(data, index);
};我刚刚创建了一个示例片段,如下所示,以便在每次单击按钮console.log(years[index].year);时,使用$scope.myFunction()中的一个成功记录ng-init的ng-init来检查这一点。
angular.module('myApp', []);
function MyCtrl($scope) {
var json = [{SecuredYear: 1965},{SecuredYear: 1988}, {SecuredYear: 2016}, {SecuredYear: 2012}];
$scope.generateChart = function(item) {
var years = [];
json.forEach(function (obj) {
var exists = years.filter(function(y) {
return y.year === obj.SecuredYear;
});
if (exists.length === 0) {
years.push({year: obj.SecuredYear});
}
});
$scope.years = years;
$scope.myFunction = function (index) {
var data = [['Product', 'ValueInDhs']];
json.forEach(function (obj) {
if (obj.SecuredYear == years[index].year) {
//data.push([String(obj.GroupName).trim(), obj.ValueInDhs]);
console.log(years[index].year);
}
});
//$scope.displayChart(data, index);
};
};
}<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<button ng-click="generateChart()">Generate Chart</button><br/>
<div style="border: 1px solid skyblue;" ng-repeat="year in years" id="piechart{{$index}}" ng-init="myFunction($index)" >{{year.year}}
</div>
</div>
</div>
发布于 2017-01-15 16:08:39
angular.module('app', [
'googlechart'
])
.controller('appCtrl', function() {
let vm = this;
vm.charts = [];
vm.addChart = function() {
vm.charts.push({
type: "PieChart",
data: {
"cols": [{
id: "t",
label: "Topping",
type: "string"
}, {
id: "s",
label: "Slices",
type: "number"
}],
"rows": [{
c: [{
v: "Mushrooms"
}, {
v: 3
}, ]
}, {
c: [{
v: vm.input.name
}, {
v: vm.input.quantity
}]
}, {
c: [{
v: "Olives"
}, {
v: 31
}]
}, {
c: [{
v: "Zucchini"
}, {
v: 1
}, ]
}, {
c: [{
v: "Pepperoni"
}, {
v: 2
}, ]
}]
}
});
};
return vm;
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-google-chart/0.1.0/ng-google-chart.min.js" type="text/javascript"></script>
<div ng-app="app" ng-controller="appCtrl as vm">
<div ng-repeat="chart in vm.charts track by $index">
<div google-chart chart="chart" style="height:150px; width:100%;"></div>
</div>
<br>
<input type="text" required ng-model="vm.input.name" placeholder="Enter name">
<input type="number" required ng-model="vm.input.quantity" placeholder="Enter quantity">
<button ng-click="vm.addChart()">Add chart</button>
</div>
我注意到你在用谷歌图表。您的问题来自于使用不兼容的库(在这种情况下,google图表不知道模型角的变化)。
您可以使用编写自己的指令,但是如果其他人已经完成了任务,为什么要这样做呢?相反,我建议您考虑使用以下指令。
下面是一个活着示例。
编辑:ng-init按照你想要的方式做而不是。ng-init只是在控制器加载时,而不是在呈现元素时触发一个函数。
https://stackoverflow.com/questions/41038466
复制相似问题