2016-07-29 113 views
0

我正在構建一個單頁應用程序AngularJS,我有一個controller設置了一個按鈕單擊運行的函數。此功能以承諾運行。當功能解決後,我正在更新根變量並更改$location路徑。但根變量和$location似乎並沒有更新。AngularJS範圍變量不在jQuery中更新承諾/推遲

請注意,這所有的代碼是從生產所示例

DOM:

<div ng-controller="ExampleController"> 
    <button ng-click="button_function('I am a variable')">Run function</button> 
</div> 

控制器:

app.controller('ExampleController', ['$scope', '$location', function($scope, $location) { 

    $scope.button_function = function(variable) { 
     $scope.$root.show_something = true; 

     my_function.something(variable).done(function(data) { 
      if (data) { 
       $scope.$root.show_something = false; 
       $location.path('/go-to-path'); 
      } else { 
       alert('Something went wrong'); 
      } 
     }]); 
    }; 

}]); 

這是my_function代碼:

var my_function = { 
    something: function(variable) { 
     var deferred = $.Deferred(); 

     var window = window.open('http://dynamic.url/', '_blank'); 

     $(window).on('loadstart', function(e) { 
      var url = e.originalEvent.url; 

      if (url === 'http://dynamic.url/expected_response') { 
       window.close(); 
       deferred.resolve({ 
        key_1: 'data', 
        key_2: 'more data' 
       }); 
      } 

     }); 

     return deferred.promise(); 
    } 
}; 

所有看起來不錯的權利?但是當my_function.something(variable)「完成」時,$location$scope.$root.show_something似乎沒有更新。

我做錯了什麼?

感謝

+0

的可能的複製[如何更新從jQuery的控制變量?(HTTP:/ /stackoverflow.com/questions/16886222/how-to-update-controller-variable-from-jquery) – Jorrex

回答

0

我找到了修復程序。

deferred後,我的控制器「完成」我包裹着我的變量$timeout

app.controller('ExampleController', ['$scope', '$location', '$timeout', function($scope, $location, $timeout) { 

    $scope.button_function = function(variable) { 
     $scope.$root.show_something = true; 

     my_function.something(variable).done(function(data) { 
      if (data) { 
       $timeout(function() { 
        $scope.$root.show_something = false; 
        $location.path('/go-to-path'); 
       }, 1); 
      } else { 
       alert('Something went wrong'); 
      } 
     }]); 
    }; 

}]); 

答發現here

0

您應該返回deferred.promise而不是deferred.promise()

- 編輯:我的壞我沒有看到你沒有使用$ q,因爲我誤讀了。