btm*_*tm1 9 if-statement angularjs
所以我正在浏览AngularJS的教程:
我在控制器中定义了一个数组,当我循环遍历ng-repeat {{feature.name}} {{feature.description}}时,我通过调用返回数组中的不同点
我不明白的是让我说数组中的第三个点叫做"重要性",它是一个从1到10的数字.我不想在html中显示那个数字,但我想做的是如果数组中的"重要性"数字是10对1,则为该要素应用不同的颜色
那么如何写一个if语句来做到这一点:
即
<p style="**insert if statement: {{if feature.importance == 10}} color:red; {{/if}} **">{{feature.description}}</p>
Run Code Online (Sandbox Code Playgroud)
不知道这是否正确,但这就是我想做的事情
Tos*_*osh 11
我认为没有if可用的声明.为了您的造型目的,ng-class可以使用.
<p ng-class="{important: feature.importance == 10 }">
Run Code Online (Sandbox Code Playgroud)
ng-switch 也方便.
- 更新 -
看看:https: //stackoverflow.com/a/18021855/1238847
angular1.2.0RC似乎有ng-if支持.
实际上Angular 1.2.0中有一个三元运算符.
<p style="{{feature.importance == 10 ? 'color:red' : ''}}">{{feature.description}}</p>
Run Code Online (Sandbox Code Playgroud)
第一个是一个指令,用于评估某些内容是否只应在 DOM 中出现一次,并且不向页面添加任何监视侦听器:
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');
});
}
}
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
第二个指令是有条件地将属性仅应用于元素一次而无需监视侦听器的指令:
IE
<div set-attr="{ data-id : post.id, data-name : { value : post.name, condition : post.name != 'FOO' } }"></div>
angular.module('setAttr',[]).directive('setAttr', function() {
return {
restrict: 'A',
priority: 100,
link: function(scope,elem,attrs) {
if(attrs.setAttr.indexOf('{') != -1 && attrs.setAttr.indexOf('}') != -1) {
//you could just angular.isObject(scope.$eval(attrs.setAttr)) for the above but I needed it this way
var data = scope.$eval(attrs.setAttr);
angular.forEach(data, function(v,k){
if(angular.isObject(v)) {
if(v.value && v.condition) {
elem.attr(k,v.value);
elem.removeAttr('set-attr');
}
} else {
elem.attr(k,v);
elem.removeAttr('set-attr');
}
});
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用角度内置的动态版本:
<div ng-class="{ 'myclass' : item.iscool }"></div>
Run Code Online (Sandbox Code Playgroud)
您还可以使用 angularjs 添加的新 ng-if,它基本上取代了 angularui 团队创建的 ui-if,这些将有条件地从 DOM 中添加和删除内容,并添加监视侦听器以继续评估:
<div ng-if="item.iscool"></div>
Run Code Online (Sandbox Code Playgroud)