2015-11-06 188 views
0

通過這段代碼,我試圖在編輯之前拿一個事件的副本,或者在事件視圖中任何改變來實現取消按鈕,所以我將它複製到了oldValue變量,但事件和oldValue總是空的,因爲(我認爲)他們在事件工廠的返回之前執行,其填充事件變量獲取範圍的舊值

我該怎麼做才能解決這個問題?

事件HTML

<sw-event-view event="ev.event" ng-hide="ev.loading" ng-if="ev.view_type == 'event'" ></sw-event-view> 

事件控制器

angular.module('App') 
     .controller('EventCtrl', function ($scope, $state, $http, EventFactory) { 
      ev.event = {}; 

      console.log('controller start'); 
      ev.view_type = 'event'; 
      EventFactory.getEvent(1) 
         .then(function(r) { 
            ev.event = r.data.data.event; 
            console.log('event controller',ev.event); 
            ev.loading = false; 
         } ,handleHttpError); 
      console.log('end of controller'); 

} 

事件視圖的HTML

<div>Something</div 
<sw-basic-info ng-show="!edit_mode && selected_tab == 'basic info'" event="event"></sw-basic-info> 

<sw-locations-list ng-show="(selected_tab == 'locations') && !edit_mode" locations="event.locations"></sw-locations-list> 

事件視圖指令

angular.module('App') 
     .directive('swEventView', function (EventFactory) { 
     return { 
      scope: { 
       event: "=", 
      }, 
     templateUrl: 'template url', 
     restrict: 'E', 
     link: function (scope, element, attrs) { 
      console.log('event view scope.event', scope.event); 
      scope.oldValue = angular.copy(scope.event); 
      console.log('event view scope.oldValue', scope.oldValue); 
     } 
    } 

事件工廠

angular.module('App') 
     .factory('EventFactory', function ($http, $q) { 

      var getEvent = function (id) { 
           console.log('event factory', id); 
           return $http.get(server + "event/"+id); 
       } 

}

那是什麼我在日誌中看到

controller start 
event factory 1 
end of controller 
event view scope.event Object {} 
event view scope.oldValue Object {} 

event controller 
Object {id: 1, event_code: "5020048072", name: "Heathcote", short_name: "Hea", description: "Dolor unde molestiae fuga culpa aut excepturi iste et esse tempore illo quia quod aut."…} 

回答

1

有可能要恢復到在角舊數據多種方式,所有的低於參與只是控制器而不是指令。

在任何更改之前恢復原始數據的情況下,您可以簡單地將數據複製到另一個變量,並在需要時替換已更改的數據。

var originalData = angular.copy($scope.data); 

$scope.reset = function() { 
    $scope.data = originalData; 
}; 

如果你想立即事件(即最後ngModel更新之前)之前恢復到的數據,一個選擇是使用$範圍。$腕錶不斷改寫存儲在一個變量的前值。

var prevData; 

$scope.$watch('data', function (nv, ov) { 
    // Add to history (create a copy) 
    prevData = angular.copy(ov); 
}, true); 

$scope.reset = function() { 
    $scope.data = prevData; 
}; 

或爲輸入你可以使用$rollbackViewValue()

$scope.cancel = function(e) { 
    // if the escape key pressed 
    if (e.keyCode == 27) { 
     $scope.formName.fieldName.$rollbackViewValue(); 
    } 
}; 

HTML代碼將是

<form name="formName" role="form"> 
    <input type="number" class="form-control" name="fieldName" ng-model="data" ng-model-options="{updateOn: 'blur'}" ng-keyup="cancel($event)"> 
</form> 
+0

謝謝親愛的,訣竅是使用$手錶功能 – user2099451