删除操作后的AngularJS更新视图

时间:2015-05-09 22:46:29

标签: javascript ruby-on-rails angularjs

我有一个执行RESTful操作的AngularJS和Rails应用程序:创建,读取,销毁。

我必须在执行'删除'后刷新页面。操作,我试图弄清楚如何异步更新视图。

'创造'操作使用.success http函数更新视图中的单词;我尝试使用删除操作类似的approch但收到错误:Cannot read property 'success' of undefined

app.js

//= require angular-rails-templates
//= require_tree .


angular.module('d-angular', ['ui.router', 'templates'])

// Set routing/configuration
// ------------------------------
.config(['$stateProvider', '$urlRouterProvider',

    // Set state providers
    function($stateProvider, $urlRouterProvider) {$stateProvider

        // Home state
        .state('home', {
          url: '/home',
          templateUrl: 'home.html',
          controller: 'MainCtrl',
          resolve: {
              listPromise: ['lists', function(lists){
                return lists.getAll();
              }]
          }
        })

        $urlRouterProvider.otherwise('home');
    }
])


// lists factory
// Factories are used to organize and share code across the app.
// ------------------------------
.factory('lists', ['$http',

    function($http){
        // create new obect with array of lists
        var o = { lists: [] };

        // get all lists
        o.getAll = function() {
            return $http.get('/lists.json').success(function(data){
                angular.copy(data, o.lists);
            });
        };

        // get specific list
        o.get = function(id) {
          return $http.get('/lists/' + id + '.json').then(function(res){
            return res.data;
          });
        };

        // create list
        o.create = function(post) {
          return $http.post('/lists.json', post).success(function(data){
            o.lists.push(data);
          });
        };

        // delete list
        o.delete = function(id) {
            $http.delete('/lists/' + id + '.json');
        }

        // add word to list
        o.addWord = function(id, word) {
          return $http.post('/lists/' + id + '/words.json', word);
        };

        o.deleteWord = function(id, word) {
            $http.delete('/lists/' + id + '/words/' + word + '.json');
        }

        return o;

    }
])


// Main controller
// ------------------------------
.controller('MainCtrl', ['$scope', '$stateParams', 'lists', '$http',

    // Main scope (used in views)
    function($scope, $stateParams, lists, $http) {

        // array of lists
        $scope.lists = lists.lists;

        $scope.list = lists.lists[$stateParams.id];


        // Add list function
        // Creates a new list
        $scope.addList = function(){
            // prevent empty titles
            if(!$scope.title || $scope.title === '') { 
                return;
            }

            lists.create({
                title: $scope.title,
                date: new Date().toJSON().slice(0,10),
            });

            // reset title
            $scope.title = '';
        };

        $scope.deleteList = function() {
            lists.delete($scope.list.id).then(function(){
                $scope.lists.splice(index, 1)
            }); // UPDATE THE VIEW
        };

        // Add word function
        $scope.addWord = function(){

                // push new word to array
                lists.addWord($scope.list.id, {
                    title: $scope.word,
                    date: new Date().toJSON().slice(0,10),
                })
                .success(function(word) {
                    $scope.list.words.push(word);
                });
            });
        };

        $scope.deleteWord = function(word_id) {
            lists.deleteWord($scope.list.id, word_id);
        };


    }

]);

视图

<div ng-controller="MainCtrl">

  <!-- add a list -->
  <form ng-submit="addList()">
    <input type="text" ng-model="title" placeholder="Enter list"></input>
    <button type="submit">Add</button>
  </form>
  <!-- end add -->

  <!-- list all lists -->
  <select ng-model="list" ng-options="list as list.title for list in lists">
      <option value="">Select List</option>
  </select>
  <!-- end list -->

  <!-- delete list -->
  <form ng-submit="deleteList()">
    <button type="submit">Delete</button>
  </form>
  <!-- end delete -->

  <hr>

  {{list.id}}

  <!-- add word -->
  <form ng-submit="addWord()">
    <input type="text" ng-model="word"></input>
    <button type="submit">Add</button>
  </form>
  <!-- end add -->

  <!-- list all words in list -->
   <div ng-repeat="word in list.words">
      {{word.title}}
      {{word.id}}

      <!-- delete word -->
      <form ng-submit="deleteWord(word.id)">
        <button type="submit">Delete</button>
      </form>
      <!-- end delete -->

  </div>
  <!-- end words -->

2 个答案:

答案 0 :(得分:2)

是不是因为你没有从$http.delete()返回值?在工厂函数中添加return语句:

    o.deleteWord = function(id, word) {
        return $http.delete('/lists/' + id + '/words/' + word + '.json');
    }

然后在您的控制器中,您可以参考.success()

    $scope.deleteWord = function(word_id) {
        lists.deleteWord($scope.list.id, word_id)
             .success(...);
    };

答案 1 :(得分:0)

澄清我的评论

假设您已经拥有o.getAll函数,您只需在成功回调中调用该函数

o.deleteWord = function(id, word) {
    return $http.delete('/lists/' + id + '/words/' + word + '.json')
    .success(function(response){ 
        return o.getAll(); 
    }):
}

我会把它放在o.deleteWord函数中。同样在你的rails控制器中,你想要在破坏你的模型后用Word.all回复。没有它,页面不会更新,因为它将监听更新的words.json,所以像

  def destroy
    Word.delete(params[:id])
    respond_with Word.all
  end