1. 程式人生 > >Angular-checked方法使用

Angular-checked方法使用

場景:

在進入修改商品頁面的時候,前端獲取從後端返回的資料,並將這些資料展示在修改商品的頁面上,在使用AngularJS的情況下如何判斷並勾選?也即:什麼時候勾選複選框?

(1)取決於資料庫中的某張表的某個欄位,例如在資料庫中儲存的是這樣的:

  [{"attributeName":"網路","attributeValue":["移動3G","移動4G"]},{"attributeName":"機身記憶體","attributeValue":["16G","32G"]}]

    (2)首先將該值取出來,然後檢查當前所迴圈的節點,將兩個值都傳遞過去(例如判斷“移動3G”,需要傳“移動3G”和“網路”),如果查詢到了則勾選,反之則無。


    (3)先檢查attributeName是否匹配,如果不匹配則直接返回false即可

 

封裝通用匹配方法:

//通用查詢方法:在list集合中根據某個key的值查詢物件
//list:待查詢集合,key:待查詢屬性的字串,待匹配的值
$scope.searchObjectByKey=function(list,key,keyValue){
	for(var i=0;i<list;i++){
		//list[i]就是查詢的每一個元素
		//將傳過來的值進行匹配,固定的key可以寫list[i]['attributeName']
		if(list[i][key]==keyValue){
			//返回的是一個物件
			return list[i];
		}
	}
	
	return null;
}

 

實體查詢方法:

//查詢實體 
$scope.findOne=function(id){
	//會獲取頁面上所有的引數,會將所有引數轉換成陣列。獲取某一個值方式:
	var id = $location.serach()['id'];
	if(id = null){
		return ;
	}		
	goodsService.findOne(id).success(
		function(response){
			$scope.entity= response;
			//富文字編輯器
			editor.html($scope.entity.goodsDesc.introduction);
			//商品圖片
			$scope.entiy.goodsDesc.itemImages = JSON.parse($scope.entiy.goodsDesc.itemImages); 
			//擴充套件屬性
			$scope.entity.goodsDesc.customAttributeItems = JSON.parse($scope.entity.goodsDesc.customAttributeItems);
			//規格選擇
			$scope.entity.goodsDesc.specificationItems = JSON.parse($scope.entity.goodsDesc.specificationItems);
			
		}
	);				
}

 

使用AngularJS的Angular-checked方法將匹配的值自動勾選:

//自動勾選
$scope.checkAttributeValue=function(specName,optionName){
	var items = $scope.entity.goodsDesc.specificationItems;
	//需要接收3個引數,第一個為list集合(哪裡來?),查詢時轉換
	var obj = $scope.searchObjectByKey(items, 'attributeName', specName);
	if(obj != null){
		//如果能查詢到則勾選
		if(obj.attributeValue.indexOf(optionName)>=0){
			return true;
		}else{
			return false;
		}
	}else{
		//obj空
		return false;
	}
}