AngularJS视图不使用延迟和工厂更新

时间:2014-04-17 22:25:49

标签: angularjs angularjs-service

我目前遇到的问题是,当我尝试创建新设置时,我的视图在刷新页面之前不会更新。有人能指出我正确的方向吗?如果我以错误的方式解决这个问题,请让我知道更好的方法。

app.factory('SettingsFactory', function ($http, $q) {
//$scope.settingData = {}

return {
  getAllOptionsAsync: function(callback) {
    var deferred = $q.defer();
    $http.get('/api/settings').success(callback);
  },
  deleteOptionAsync: function(id) {
    //console.log('reached');
    var deferred = $q.defer();
    $http.delete('/api/settings/' + id);
  },
  createOptionAsync: function(settingData) {
    var deferred = $q.defer();
    $http.post('/api/settings', settingData).success(function(data) { console.log(data); 
                                                deferred.resolve(data);
                                               // console.log(deferred.promise);
                                                return deferred.promise;
                                              });
  }


};


});


var controllers = {};
controllers.SettingsController = function($scope, SettingsFactory) {

//$scope.settings = SettingService.list();
SettingsFactory.getAllOptionsAsync(function(results) {
  //console.log(results);
  $scope.settings = results;
});

$scope.create = function() {
               // console.log('called');
               // console.log($scope.formData);
                SettingsFactory.createOptionAsync($scope.formData).then(function(data) {
                  console.log(data);
                  $scope.settings = data;
                });
              } 

 $scope.delete = function(id) {
                //console.log(id.entity._id);
                SettingsFactory.deleteOptionAsync(id.entity._id);
              }


$scope.gridOptions = { 
data: 'settings',
multiSelect: false,
columnDefs: [
  {field: 'option'},
  {field: 'value'},
  {displayName: 'Edit', cellTemplate: '<button id="editBtn" type="button" class="btn btn-primary" ng-click="open(settings._id)" >Edit</button> <button id="deleteBtn" type="button" class="btn btn-primary" ng-click="delete(row)" >Edit</button> '}
]
};
}

1 个答案:

答案 0 :(得分:0)

在当时或任何时候更新回调范围时,需要使用scope.apply包装$ scope.settings = data。

$scope.$apply(function() {
    $scope.settings=data;
 });

在手机上键入,以便可能出错。