使用json的模型数据进行角度排序

时间:2014-10-16 06:48:32

标签: json angularjs

我想在我的应用上使用角度排序。但我的模型是使用$http.get()函数从几个json文件动态填充的。从模型中看到的所有ngSortable都只是一个空数组。它无法从JSON文件中获取新数据。有没有解决方法呢?



$scope.jsons = ["data1.json", "data2.json"];
$scope.abc = [];

angular.forEach($scope.jsons, function(value, key){
	$http.get(value).success (function(data){
		$scope.abc.push(data);
	});
});

$scope.sortableOptions = {
  accept: function (sourceItemHandleScope, destSortableScope) {return true}
};

<div ng-model="abc" as-sortable="sortableOptions">
	<div ng-repeat="x in abc" as-sortable-item>
		<div as-sortable-item-handle>{{x.name}}</div>
	</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我在ng-sortable方面遇到了同样的问题:静态数据一切正常但与$ http.get()异步的JSON数据无关。

有两种解决方案:

  1. 将控制器保留为原样,在html部分中,将“abc”的两次出现替换为“$ parent.abc”

  2. 不要直接访问'abc'数组,而是使用中间对象,如下所示:

    $scope.tmpObject = {};
    $scope.tmpObject.abc=[];
    ...
    $http.get(value).success (function(data){
        $scope.tmpObject.abc.push(data);
    }); 
    

    ...

    <div ng-model="tmpObject.abc" as-sortable="sortableOptions">
        <div ng-repeat="x in tmpObject.abc" as-sortable-item>
            <div as-sortable-item-handle>{{x.name}}</div>
        </div>
    </div>
    

答案 1 :(得分:0)

使用service $q

//first make a factory using $q

yourappname.factory("factoryname",function($http, $q){
    var _getDetails=function(value){

        var deferred = $q.defer();
        $http.get(value).then(function(modal){

            deferred.resolve(modal);
        });

        return deferred.promise;

    };
  return  {
    _getDetails:_getDetails
  
};
  });

// then in your controller use this factory

$scope.jsons = ["data1.json", "data2.json"];
$scope.abc = [];


/**angular.forEach($scope.jsons, function(value, key){
	$http.get(value).success (function(data){
		$scope.abc.push(data);
	});
});
***/
angular.forEach($scope.jsons, function(value, key){
           var promiseData= factoryname._getDetails(value);
           promiseData.then(function(result){
           if(result.data)
            {
              $scope.abc.push(result.data);
              
            }
              
           });
});                  
$scope.sortableOptions = {
  accept: function (sourceItemHandleScope, destSortableScope) {return true}
};
<div ng-model="abc" as-sortable="sortableOptions">
	<div ng-repeat="x in abc" as-sortable-item>
		<div as-sortable-item-handle>{{x.name}}</div>
	</div>
</div>