[英]AngularJS ng-repeat not re-rendering the repeater (UI) and not invoking ng-init once again
我對ng-init
有一點疑問,實際上我有一些圖表。
在頁面加載我沒有顯示任何內容,但是一旦我第一次點擊特定按鈕,我的整個圖表和表格將顯示為http請求收到的數據。 但之后如果我點擊另一個按鈕並執行相同的http請求,那么它會更新趨勢線和表,但不會更新餅圖。 我的餅圖使用ng-init在下面的div中呈現,當我測試ng-init =“myFunction(index)”方法時,它不會在后續點擊中更新。
<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-init函數的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
從
Angular 1.2
,它有一個選項track by
以防止轉發器重新渲染所有項目以提高性能。
更多信息請訪問: http : //www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/
這就是為什么ng-init
在相同的years
再次被解雇的原因,因為你已經在這里使用了track by
ng-repeat="year in years track by $index"
。
即使你刪除它, ng-init
也是第二次沒有被觸發,因為這里years
是Angular
非常強大的數組,它可以通過它的值進行跟蹤,盡管沒有明確的track by
。
因此,我們必須將years
從簡單數組更改為object array
如[{year: obj.SecuredYear}]
,讓Angular生成一個$$hashKey
,當對象每次更改時,它都不相同,而Angular將重繪轉發器通過觸發ng-init
。
所以與此相關的變化是,
HTML
<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);
在每次單擊“ Generate Chart
”按鈕時,使用ng-init
成功記錄的$scope.myFunction()
內部。
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>
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>
我注意到你正在使用谷歌圖表。 您的問題來自於使用不兼容的庫(谷歌圖表不知道模型中的變化 - 在這種情況下是角度)。
你可以編寫自己的指令,但為什么如果其他人已經完成了繁重的工作? 相反,我建議您考慮使用以下指令 。
這里有一個活例子。
編輯: ng-init
不能按您希望的方式工作。 ng-init
只是在控制器加載時觸發一個函數,而不是在渲染元素時觸發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.