如何实现“ui-sref"?有条件执行? [英] How to achieve that "ui-sref" be conditionally executed?
问题描述
我想在浏览器跟随 ui-router 动态创建的链接之前验证某些条件.
I want to validate certain condition before the browser follow the link dynamically created by ui-router.
我正在查看 $rootscope.$on('$stateChangeStart', ..)
但我无法从那里访问 controller.$scope
.我还需要在应用程序的几个地方使用它,这会很麻烦.
I was looking into $rootscope.$on('$stateChangeStart', ..)
but I have no access to the controller.$scope
from there. I also need to use this in several places in the application and would be cumbersome.
请记住,ui-sref
已链接到 ui-sref-active
(协同工作),因此我无法删除 ui-sref
并且,比如说,在使用 ng-click
调用的函数中使用 $state.$go('some-state')
.
Keep in mind that ui-sref
is linked to ui-sref-active
(work together), so i can't remove ui-sref
and, by say, to use $state.$go('some-state')
inside a function called with ng-click
.
应该在 $scope 函数
和 on-click 事件
内评估条件(转换前可以取消它)
The condition should be evaluated inside a $scope function
and on on-click event
(before-transition with the ability to cancel it)
我需要这样的东西:
<li ui-sref-active="active">
<a ui-sref="somestate" ui-sref-if="model.validate()">Go Somestate</a>
</li>
我试过了:
<li ui-sref-active="active">
<a ui-sref="somestate" ng-click="$event.preventDefault()">Go Somestate</a>
</li>
<li ui-sref-active="active">
<a ui-sref="somestate" ng-click="$event.stopImmediatePropagation()">Go Somestate</a>
</li>
和
<li ui-sref-active="active">
<a ui-sref="somestate">
<span ng-click="$event.stopPropagation();">Go Somestate</span>
</a>
</li>
偶数
<li ui-sref-active="active">
<a ui-sref="somestate" onclick="return false;">Go Somestate</a>
</li>
但不起作用.
推荐答案
这个 answer 启发我创建了一个指令,允许我中断最终改变状态的事件链.为方便起见,其他用途也防止在同一元素上执行 ng-click.
This answer inspired me to create a directive that allows me to interrupt the chain of events that end up changing state. For convenience and other uses also prevents the execution of ng-click on the same element.
javascript
module.directive('eatClickIf', ['$parse', '$rootScope',
function($parse, $rootScope) {
return {
// this ensure eatClickIf be compiled before ngClick
priority: 100,
restrict: 'A',
compile: function($element, attr) {
var fn = $parse(attr.eatClickIf);
return {
pre: function link(scope, element) {
var eventName = 'click';
element.on(eventName, function(event) {
var callback = function() {
if (fn(scope, {$event: event})) {
// prevents ng-click to be executed
event.stopImmediatePropagation();
// prevents href
event.preventDefault();
return false;
}
};
if ($rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
},
post: function() {}
}
}
}
}
]);
html
<li ui-sref-active="active">
<a ui-sref="somestate" eat-click-if="!model.isValid()">Go Somestate</a>
</li>
这篇关于如何实现“ui-sref"?有条件执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!