[英]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.