我是AngularJS的新手。我想要一些对象名称,在运行时选择并计算如下:
$scope.filenames = [
{ name: 'abc', selected: false , count: 10},
{ name: 'ede', selected: false, count: 5},
{ name: 'xyz', selected: false, count: 2 },
{ name: 'pqe', selected: false, count: 8 }
];
所以我创建了restangular服务,用于获取name,count和运行时选择的值。获取运行时这些值的代码是:
//initialize the arrays
$scope.filenames=[];
$scope.filenames.count=[];
$scope.filenames.name=[];
$scope.filenames.selected=[];
//called rest service that fetch the names of all files
Restangular.one("getAllFiles").get().then(function(listAllFiles){
for(i=0;i<listAllFiles.length;i++){
var fileName=listAllFiles[i];
//then called another rest service that return the file name along with the count like abc=2
var parameter="getFileCount/fileName;
Restangular.one(parameter).get().then(function(countAndFileName){
var spilitFileCount=countAndFileName.split("myspiliter");
$scope.filenames.name.push(spilitFileCount[0]);
$scope.filenames.selected.push(false);
$scope.filenames.count.push(spilitFileCount[1]);
});
}
});
我能够成功获得计数和文件名。我希望他们都放入$scope.filenames
数组。这样我就可以在我的html页面上使用这个数组:
显示文件名和计数的Html代码是:
<div class="form-group" id="filename" style="display:none;">
<label class="col-sm-8 control-label" ng-repeat="filename in filenames">
<input
type="checkbox"
name="myName[]"
value="{{filenames.name}}"
ng-model="filenames.selected"
ng-click="toggleSelection(filename.name)"
> {{filename.name}} ({{filename.count}})
</label>
</div>
但我无法将值放入数组$scope.filenames
并在HTML视图中使用它。如果我在外部休息服务之外访问$scope.filenames
的值,那么它什么都没有。我错过了什么?
答案 0 :(得分:0)
您的代码与您想要的完全匹配。你想要的是:
$scope.filenames = [
{ name: 'abc', selected: false, count: 10},
{ name: 'ede', selected: false, count: 5},
{ name: 'xyz', selected: false, count: 2},
{ name: 'pqe', selected: false, count: 8}
];
这是一个单个数组,包含对象。
但是您的代码执行以下操作:
$scope.filenames = [];
$scope.filenames.count=[];
$scope.filenames.name=[];
$scope.filenames.selected=[];
这会创建4个数组。
你想要的是
$scope.filenames = [];
并且您希望在此数组中推送具有3个属性的对象:
var spilitFileCount = countAndFileName.split("myspiliter");
var object = {
name: spilitFileCount[0],
selected: false,
count: spilitFileCount[1]
};
$scope.filenames.push(object);
你的ng-repeat体也是错的:
<label class="col-sm-8 control-label" ng-repeat="filename in filenames">
以上意思是:遍历数组filenames
;在每次迭代中,可以使用变量filename
访问当前元素。
所以它不应该是
value="{{filenames.name}}"
ng-model="filenames.selected"
但
value="{{filename.name}}"
ng-model="filename.selected"