AngularJS:从新模板访问延迟承诺

AngularJS:从新模板访问延迟承诺,angularjs,angularjs-service,angular-promise,angularjs-factory,Angularjs,Angularjs Service,Angular Promise,Angularjs Factory,我是angular的新手,我很喜欢它……来自10年的PHP背景,对我来说有很多新术语。 这是我想做的,不确定是否可能,如果可能,不确定如何做。我已经创建了一个属性列表,该部分工作正常。该列表显示每个属性的有限详细信息,所有详细信息都可用于详细视图 所以我的问题是,如何通过id访问数据,而不必再次点击数据库并在新模板中显示详细视图 以下是我目前掌握的代码: propApp.controller('propertyCrtl', function ($scope, $routeParams, $tim

我是angular的新手,我很喜欢它……来自10年的PHP背景,对我来说有很多新术语。 这是我想做的,不确定是否可能,如果可能,不确定如何做。我已经创建了一个属性列表,该部分工作正常。该列表显示每个属性的有限详细信息,所有详细信息都可用于详细视图

所以我的问题是,如何通过id访问数据,而不必再次点击数据库并在新模板中显示详细视图

以下是我目前掌握的代码:

propApp.controller('propertyCrtl', function ($scope, $routeParams, $timeout, getProperty ) {

  var promise = getProperty.getList();
  promise.then(function(data){
    $scope.list = data.data.listings;
    $scope.id = $routeParams.prop_id;
    $scope.currentPage = 1; //current page
    $scope.entryLimit = 20; //max no of items to display in a page
    $scope.filteredItems = $scope.list.length; //Initially for no filter
    $scope.totalItems = $scope.list.length;
    //console.log(data.data.listings);
  })
服务呢

propApp.service('getProperty', function($http, $q){

var deferred = $q.defer();
$http.get('wp-content/themes/wp-angular-theme/ajax/getProperty.php')
.then(function(data){
  deferred.resolve(data);
});

this.getList = function(){
  return deferred.promise;
}

this.getById = function(id){
  return deferred.promise;
} 

})

感谢您的帮助。

如果您没有对数据进行任何修改或验证,则无需创建新的承诺
$http.get
返回承诺本身,您可以利用
$http
对象承诺本身

服务

propApp.service('getProperty', function($http, $q) {

    this.getList = function() {
        return $http.get('wp-content/themes/wp-angular-theme/ajax/getProperty.php');
    }

    this.getById = function(id) {
        return $http.get('wp-content/themes/wp-angular-theme/ajax/getProperty.php?id=' + id);
    }

})

您可以像这样修改
getByid
方法

this.getById = function(id){
   var def = $q.defer();
   deferred.promise.then(function(data){
      //find the matching list
      for (var i = 0;i <data.data.listings.length;i++) {
         if (data.data.listings[i].id == id) {
            def.resolve(data.data.listings[i]);    
            return;
         }
      }
      //Reject the promise here because we didn't find the matching id
      def.reject();
   });   
   return def;
} 
服务

propApp.service('getProperty', function($http, $q){

  this.getList = function(){
    return $http.get('wp-content/themes/wp-angular-theme/ajax/getProperty.php')
  }

});

为什么我们需要创建额外的承诺?我知道这不是必需的,因为
$http
给了我们承诺。但我认为OP正在努力维持这一承诺,这样他就可以在不提出新请求的情况下再次获取列表或列表详细信息。实际上,由于列表已经在
$scope
中可用,我们从
$scope.list
本身获取列表详细信息。您正在谈论控制器级别。您能解释一下他如何避免第二次访问吗请求..?OP提到所有详细信息都已提供,因此我们不需要第二次呼叫。
propApp.service('getProperty', function($http, $q){

  this.getList = function(){
    return $http.get('wp-content/themes/wp-angular-theme/ajax/getProperty.php')
  }

});