"ui-sref"를 조건부로 실행하는 방법은 무엇입니까?
브라우저가 ui-router에 의해 동적으로 생성 된 링크를 따르기 전에 특정 조건을 확인하고 싶습니다.
찾고 $rootscope.$on('$stateChangeStart', ..)
있었지만 controller.$scope
거기에서 액세스 할 수 없습니다 . 또한 응용 프로그램의 여러 위치에서 이것을 사용해야하고 번거로울 것입니다.
그것은 (함께 작동)에 ui-sref
연결되어 ui-sref-active
있으므로 제거 할 수 없으며 라는 함수 내 ui-sref
에서 사용할 수 없습니다 .$state.$go('some-state')
ng-click
조건은 a $scope function
및 on on-click event
(취소 할 수있는 전환 전) 내에서 평가되어야합니다.
다음과 같은 것이 필요합니다.
<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>
그러나 작동하지 않습니다.
이 답변 은 상태가 변경되는 일련의 이벤트를 중단 할 수있는 지침을 만들도록 영감을주었습니다. 편의 및 기타 사용을 위해 동일한 요소에 대한 ng-click 실행을 방지합니다.
자바 스크립트
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>
다음 중 하나를 반환하는 범위 함수를 사용할 수 있습니다.
- 상태 없음
기존 상태
이렇게 :
HTML :
<li ui-sref-active="active">
<a ui-sref="{{checkCondition()}}">Go Somestate</a>
</li>
JS 범위 :
$scope.checkCondition = function() {
return model.validate()
? 'someState'
: '-' // hack: must return a non-empty string to prevent JS console error
}
href
속성은 함수가 기존 상태 문자열을 반환 할 때만 생성됩니다.
또는 다음을 수행 할 수 있습니다.
<li ui-sref-active="active">
<a ui-sref="somestate" ng-if="model.validate()">Go Somestate</a>
<span ng-if="!model.validate()">Go Somestate</span>
</li>
도움이 되었기를 바랍니다
가장 쉬운 해결 방법은 조건부 지시 땜질없이 라우팅을 달성하는 등 범위 내가 여기 해결했다 - https://github.com/angular-ui/ui-router/issues/1489
<a ui-sref="{{condition ? '.childState' : '.'}}"> Conditional Link </a>
항상 요소를 두 배로 늘리고 조건부로 표시 / 숨길 수 있습니다.
<li ui-sref-active="active">
<a ng-show="condition1" style="color: grey">Start</a>
<a ng-hide="condition1" ui-sref="start">Start</a>
</li>
http://plnkr.co/edit/ts4yGW?p=preview
No need for complicated directives or hacks. The following works fine and allows for specific handling on click of non-sref
items:
<a
ng-repeat="item in items" ui-sref="{{item.sref || '-'}}"
ng-click="$ctrl.click(item, $event)"
>...</a>
And in the controller, a simple click handler for the items which don't have an item.sref
:
this.click = function(item, event) {
if (!item.sref) {
event.preventDefault();
//do something else
}
};
Based on the answers to How to dynamically set the value of ui-sref
you can create a function in your scope for building the URL:
$scope.buildUrl = function() {
return $state.href('somestate', {someParam: 'someValue});
};
And then conditionally append it to the link with ng-href
<a ng-href="{{ someCondition ? buildUrl() : undefined }}">Link</a>
As you can see in the demo below, ng-href
does not add the href
attribute if value is negative.
angular.module('app', [])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<a ng-href="{{ condition ? 'http://thecatapi.com/api/images/get?format=src&type=gif' : undefined}}">This is the link</a>
<br>
<label for="checkbox">
<input type="checkbox" id="checkbox" ng-model="condition">
Link active?
</label>
</div>
I know this is an old question, but for future reference I wanted to offer an alternative solution since I didn't see it in any of the answers so far.
Desired:
<li ui-sref-active="active">
<a ui-sref="somestate" ui-sref-if="model.validate()">Go Somestate</a>
</li>
Potential solution (template):
<li ng-class="{ active: state.current.name === 'somestate' }">
<a ng-click="navigateToState()">Go Somestate</a>
</li>
And in the controller:
$scope.state = $state;
$scope.navigateToState = navigateToState;
function navigateToState() {
if ($scope.model.valid) {
$state.go('somestate');
}
}
Possible solution for those who still need ng-click
working on ui-sref
component or its parents.
My solution is to use href
instead of ui-sref
and to modify Emanuel's directive a bit to be able to stop href
and ng-click
calls separately.
Though it has a few restrictions:
- will not work with
ui-sref
- you should have different urls for each state because of previous restriction
ui-sref-active
will not work either
참고URL : https://stackoverflow.com/questions/25600071/how-to-achieve-that-ui-sref-be-conditionally-executed
'IT TIP' 카테고리의 다른 글
치명적인 오류 : 정의되지 않은 함수 mb_strlen () 호출 (0) | 2020.12.07 |
---|---|
NodeJS는 정말 단일 스레드입니까? (0) | 2020.12.07 |
dplyr의 mutate_each / summarise_each : 특정 열을 선택하고 변경된 열에 새 이름을 지정하는 방법은 무엇입니까? (0) | 2020.12.07 |
if 문 다음에 나오는 변수 선언 (0) | 2020.12.07 |
페이지의 특정 부분 만 표시하는 iframe (0) | 2020.12.07 |