[英]Angular $location change path works second time, not first time
The code seems simple, but as I read the docs for $location , I notice there's a LOT of complexity I don't understand. 代码看起来很简单,但是当我阅读$ location的文档时 ,我注意到我不了解很多复杂性。 My setup is as follows: 我的设置如下:
// in app.js
$routeProvider.when('/done' , {templateUrl: 'partials/done.html', controller: 'DoneController'});
// in my controller where $location is injected, on a button press...
if (!$scope.errors.length) {
$scope.model.save().then(function() {
alert("did I get here?");
$location.path('/done');
});
}
I press the button and see the alert, but no change in view. 我按下按钮,然后看到警报,但视图没有变化。 I press the button a second time (saving data to the cloud a second time), I see the alert a second time and the view does change. 我第二次按下按钮(第二次将数据保存到云中),第二次看到警报,并且视图确实发生了变化。 Any ideas why? 有什么想法吗? Thanks in advance. 提前致谢。
I believe there must be something asynchronous in your sequence. 我相信您的序列中一定有异步的东西。 It generally happens when using an external libraries like jQuery. 通常在使用jQuery之类的外部库时发生。
The problem is that the $watch -> $digest -> $apply
cycle of angular is not triggered with external libraries events. 问题在于,外部库事件不会触发$watch -> $digest -> $apply
的角度循环。 So the change has been made, but not propagated by angularjs. 因此已进行了更改,但未由angularjs传播。
Using $scope.$apply()
will solve your problem 使用$scope.$apply()
将解决您的问题
if (!$scope.errors.length) {
$scope.model.save().then(function() {
alert("did I get here?");
$scope.$apply(function(){
$location.path('/done');
});
});
}
i am not sure why? 我不确定为什么吗? but this may be your html problem.if your html like this: 但这可能是您的html问题。如果您的html如下所示:
<a href="#" class="btn" ng-click="myFunction()">submit here</a>
then do href=""
means code should be like this: 然后do href=""
表示代码应如下所示:
<a href="" class="btn" ng-click="myFunction()">submit here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.