angular.js의 인라인 조건
ng-show 등을 사용하지 않고 콘텐츠를 조건부로 표시하는 방법이 각도인지 궁금합니다. 예를 들어 backbone.js에서 다음과 같은 템플릿에서 인라인 콘텐츠로 무언가를 수행 할 수 있습니다.
<% if (myVar === "two") { %> show this<% } %>
하지만 각도에서는 html 태그로 싸인 것을 표시하고 숨기는 것으로 제한됩니다.
<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>
html 태그로 콘텐츠를 줄 바꿈하는 대신 {{}}을 사용하여 인라인 콘텐츠를 조건부로 표시하고 숨기려면 각도에서 권장되는 방법은 무엇입니까?
편집 : 2Toad의 답변 은 당신이 찾고있는 것입니다! 저것을 찬성하십시오
Angular <= 1.1.4를 사용하는 경우이 답변은 다음과 같습니다.
이것에 대한 또 하나의 대답. 가능한 솔루션 목록보다 솔루션에 대한 "정확한"시도이기 때문에 별도의 답변을 게시하고 있습니다.
다음은 "즉시 if"(일명 iif)를 수행하는 필터입니다.
app.filter('iif', function () {
return function(input, trueValue, falseValue) {
return input ? trueValue : falseValue;
};
});
다음과 같이 사용할 수 있습니다.
{{foo == "bar" | iif : "it's true" : "no, it's not"}}
Angular 1.1.5 는 삼항 연산자에 대한 지원을 추가했습니다.
{{myVar === "two" ? "it's true" : "it's false"}}
이 고양이를 피부에 바르는 수천 가지 방법. 귀하가 {{}} 사이에서 구체적으로 질문하고 있음을 알고 있지만 여기에 오는 다른 사람들에게는 다른 옵션 중 일부를 보여줄 가치가 있다고 생각합니다.
$ scope에서 기능 (IMO, 이것은 대부분의 시나리오에서 가장 좋은 방법입니다) :
app.controller('MyCtrl', function($scope) {
$scope.foo = 1;
$scope.showSomething = function(input) {
return input == 1 ? 'Foo' : 'Bar';
};
});
<span>{{showSomething(foo)}}</span>
물론 ng-show 및 ng-hide :
<span ng-show="foo == 1">Foo</span><span ng-hide="foo == 1">Bar</span>
<div ng-switch on="foo">
<span ng-switch-when="1">Foo</span>
<span ng-switch-when="2">Bar</span>
<span ng-switch-default>What?</span>
</div>
Bertrand가 제안한 사용자 정의 필터. (이것은 동일한 일을 반복해서 해야하는 경우 최선의 선택입니다)
app.filter('myFilter', function() {
return function(input) {
return input == 1 ? 'Foo' : 'Bar';
}
}
{{foo | myFilter}}
또는 사용자 지정 지시문 :
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
link: function(scope, elem, attrs) {
scope.$watch(attrs.value, function(v) {
elem.text(v == 1 ? 'Foo': 'Bar');
});
}
};
});
<my-directive value="foo"></my-directive>
Personally, in most cases I'd go with a function on my scope, it keeps the markup pretty clean, and it's quick and easy to implement. Unless, that is, you're going to be doing the same exact thing over and over again, in which case I'd go with Bertrand's suggestion and create a filter or possibly a directive, depending on the circumstances.
As always, the most important thing is that your solution is easy to maintain, and is hopefully testable. And that is going to depend completely on your specific situation.
I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
The same approach should work for other attribute types.
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
I have published an article on working with AngularJS+SVG that talks about this and related issues. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
For checking a variable content and have a default text, you can use:
<span>{{myVar || 'Text'}}</span>
If I understood you well I think you have two ways of doing it.
First you could try ngSwitch and the second possible way would be creating you own filter. Probably ngSwitch is the right aproach but if you want to hide or show inline content just using {{}} filter is the way to go.
Here is a fiddle with a simple filter as an example.
<div ng-app="exapleOfFilter">
<div ng-controller="Ctrl">
<input ng-model="greeting" type="greeting">
<br><br>
<h1>{{greeting|isHello}}</h1>
</div>
</div>
angular.module('exapleOfFilter', []).
filter('isHello', function() {
return function(input) {
// conditional you want to apply
if (input === 'hello') {
return input;
}
return '';
}
});
function Ctrl($scope) {
$scope.greeting = 'hello';
}
Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4
Example: Support in Angular UI upto ui 1.1.4
<div ui-if="array.length>0"></div>
ng-if available in all the angular version after 1.1.4
<div ng-if="array.length>0"></div>
if you have any data in array variable then only the div will appear
So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )
This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}
{{vm.StateName === "AA" ? "ALL" : vm.StateName}}
if you want to display "None" when value is "0", you can use as:
<span> {{ $scope.amount === "0" ? $scope.amount : "None" }} </span>
or true false in angular js
<span> {{ $scope.amount === "0" ? "False" : "True" }} </span>
Works even in exotic Situations:
<br ng-show="myCondition == true" />
I'll throw mine in the mix:
https://gist.github.com/btm1/6802312
this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
참고URL : https://stackoverflow.com/questions/14164371/inline-conditionals-in-angular-js
'IT' 카테고리의 다른 글
유니 코드와 UTF-8의 차이점은 무엇입니까? (0) | 2020.05.14 |
---|---|
모니터 해상도에 관계없이 JFrame이 가운데에 나타나도록 설정하는 방법은 무엇입니까? (0) | 2020.05.14 |
HttpOnly 쿠키는 AJAX 요청과 어떻게 작동합니까? (0) | 2020.05.14 |
cplusplus.com의 문제점은 무엇입니까? (0) | 2020.05.14 |
이 새로운 ASP.NET 보안 취약점은 얼마나 심각하며 어떻게 해결할 수 있습니까? (0) | 2020.05.14 |