我有这个控制器功能:
$scope.keypadEnter = function () {
userService.isCodeValid($scope.code).then(function (result)
{
if (JSON.parse(result.data)) {
$scope.highlight("lime").then(function () {;
console.log("redirecting ...");
$location.path('/clockin');
});
}
else
{
$scope.highlight("red");
}
$scope.code = "";
});
};
控制器调用服务(userService)函数(isCodeValid),如果指定的代码有效则返回true,否则返回false。
仔细看看这两行:
$scope.highlight("lime");
$location.path('/clockin');
$ scope.highlight是一个指令函数,用于触发jquery(突出显示)动画:
angular.module('clockin').directive('grDisplay', function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
$scope.highlight = function (color) {
$element.effect("highlight", { color: color }, 500);
}
}
};
});
我希望这两行能够同步执行,以便能够在重定向之前看到高亮动画($scope.highlight(...)
)({{1 }})。
我该怎么做?
更新:
我已将指令代码更改为以下内容(我已将超时时间延长至5秒):
$location.path(...)
我的控制器功能如下:
angular.module('clockin').directive('grDisplay', function ($q, $timeout) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
$scope.highlight = function (color) {
var deferred = $q.defer();
$element.effect("highlight", { color: color }, 500)
$timeout(deferred.resolve(), 5000);
return deferred.promise;
}
}
};
});
运行时,我仍然会得到相同的结果:我可以看到突出显示,但在重定向时没有时间完成。
我有这个错误:
$scope.keypadEnter = function () {
userService.isCodeValid($scope.code).then(function (result)
{
if (JSON.parse(result.data)) {
$scope.highlight("lime").then(function () {;
console.log("redirecting ...");
$location.path('/clockin');
});
}
else
{
$scope.highlight("red");
}
$scope.code = "";
});
};
在completeOutstandingRequest上的(hxxp:// localhost:18000 / Scripts / angular.js:14261:11) (hxxp:// localhost:18000 / Scripts / angular.js:4387:7)匿名函数 (hxxp://本地主机:18000 /脚本/ angular.js:4688:7)
有什么想法吗?
答案 0 :(得分:0)
您可以在$scope.highlight
函数调用中使用延迟。该函数可以返回延迟,并在解决后,您更改$location.path
。
如果这种情况发生得太快而无法在物理上看到突出显示,那么您还可以在延迟解析时添加$timeout
:
function MyDirective($q, $timeout) {
controller : function ($scope, $element) {
$scope.highlight = function () {
var deferred = $q.defer();
// do your highlight stuff
// Resolve the deferred a second later
$timeout(deferred.resolve, 1000);
return deferred.promise;
}
}
);
然后你会调用这样的函数:
$scope.highlight("lime").then(function () {
$location.path('/clockin');
});
答案 1 :(得分:0)
你可以只看$ userService.isCodeValid($ scope.code)返回的值?
类似的东西:
$scope.val = userService.isCodeValid($scope.code);
$scope.$watch('val', function() {
if($scope.val === true){
$scope.highlight("lime");
$location.path('/clockin');
}
else {
$scope.highlight("red");
}
});
请注意,我不是JS专家,很多人都会说这是脏代码:)