[英]AngularJS ng-init not working with ng-repeat
我一直試圖在頁面初始化時調用passID()
函數,但該函數仍然無法正常工作。
網站的工作方式如下: Page-A將數據傳遞給Controller-A,然后傳遞給Service,然后傳遞給Controller-B,然后Controller-B的功能被Page-B調用。
我的猜測是,自從我成功地將Page-A的數據傳遞到Controller-B以來,我的錯誤在Page-B中,但是我不確定100%。
在我的Page-A中 ,我做了一個按鈕,使用ng-Click調用Controller-A的功能。
<a href="#/compare-details"><button class="viewDetails" ng-click="passID([1,03,07])">test button</button></a>
控制器A僅從頁面A獲取數據
angular.module('handsetExplorerModule')
.controller("compareHandsetController", ['$scope','compareHandsetService','sharedData', function($scope, compareHandsetService, sharedData) {
$scope.passID = function(id){
var arrayID = [];
arrayID = id;
sharedData.set(arrayID);
};
}]);
服務獲取我的JSON,並且是我的獲取器和設置器
angular.module('handsetExplorerModule')
.factory('compareDetailsService', ['$http','$q', function($http, $q) {
return {
getHandsetList: function(){
return $http.get("./data/compareJSON.json");
}
};
}]);
angular.module('handsetExplorerModule')
.factory('sharedData', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
Controller-B過濾JSON文件以僅獲取我需要的內容(我使用了Page-A中的ID進行過濾)
angular.module('handsetExplorerModule')
.controller("compareDetailsController", ['$scope','compareDetailsService','sharedData', function($scope, compareDetailsService, sharedData) {
$scope.data = {phones: []};
compareDetailsService.getHandsetList()
.then(
function(data){
$scope.data.phones = data.data;
},
function(error){
//todo: handle error
}
);
var getData = sharedData.get();
$scope.passID = function passID(){
var newData = [];
for(var i=0; i<$scope.data.phones.length; i++){
if($scope.data.phones[i].id == getData[0] || $scope.data.phones[i].id == getData[01] || $scope.data.phones[i].id == getData[02]){
newData.push($scope.data.phones[i]);
}
}
$scope.phoneContent = newData;
}
$scope.viewDetails = function(id){
alert(id);
}
}]);
最后,在我的Page-B中 ,我調用了Controller-B函數: <div ng-init="passID()">
由我的Page-B的 ng-repeat使用:
<table id="Content" ng-repeat="x in phoneContent track by x.id">
<tr>
<td class="one">
<table>
<tr>
<td><img class="contImage" ng-src="{{x.image}}" ng-alt="{{x.name}}" /></td>
<td class="textAlign">{{x.name}} <button class="viewDetails" ng-click="viewDetails(x.id)">VIEW DETAILS</button></td>
</table>
</td>
<td class="two">{{x.size}}</td>
<td class="one">{{x.storage}}</td>
<td class="two">{{x.camera}}</td>
<td class="one">{{x.battery}}</td>
<td class="two">{{x.network}}</td>
<td class="one">{{x.sim}}</td>
</tr>
</table>
我不知道為什么要定義arrayID
。 要解決您的問題,請嘗試使用sharedData.set = arrayID;
而不是sharedData.set(arrayID);
。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.