2016-07-29 115 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,因为我误读了。