Angularjs 表达式检查 "in array"
Angularjs expression checking for "in array"
我正在寻找最流畅的方式来做这样的事情:
<span x-ng-show="stuff && stuff.id in [1,2,5]">{{stuff.name}}</span>
<span x-ng-show="stuff && stuff.id in [3,4,6]">{{stuff.fullName}}</span>
我知道这在 AngularJS 中行不通,但我希望您能理解我的意图。最好的可读解决方案是什么?
不幸的是,我需要一个也适用于 IE11 的解决方案
如果我没理解错的话,这应该是一个简单的检查数组是否包含某些东西的方法
[1,2,5].includes(stuff.id)
工作示例
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.stuff = {
id: 5,
name: 'foo'
}
$scope.toggle = function() {
$scope.stuff.id = $scope.stuff.id === 5 ? 8 : 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span x-ng-show="stuff && [1,2,5].includes(stuff.id)">{{stuff.name}}</span>
<button ng-click="toggle()">Toggle id between 5 and 8</button>
<pre>stuff.id = {{stuff.id}}</pre>
</div>
< IE11
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.stuff = {
id: 5,
name: 'foo'
}
$scope.toggle = function() {
$scope.stuff.id = $scope.stuff.id === 5 ? 8 : 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span x-ng-show="stuff && [1,2,5].indexOf(stuff.id) > -1">{{stuff.name}}</span>
<button ng-click="toggle()">Toggle id between 5 and 8</button>
<pre>stuff.id = {{stuff.id}}</pre>
</div>
我正在寻找最流畅的方式来做这样的事情:
<span x-ng-show="stuff && stuff.id in [1,2,5]">{{stuff.name}}</span>
<span x-ng-show="stuff && stuff.id in [3,4,6]">{{stuff.fullName}}</span>
我知道这在 AngularJS 中行不通,但我希望您能理解我的意图。最好的可读解决方案是什么?
不幸的是,我需要一个也适用于 IE11 的解决方案
如果我没理解错的话,这应该是一个简单的检查数组是否包含某些东西的方法
[1,2,5].includes(stuff.id)
工作示例
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.stuff = {
id: 5,
name: 'foo'
}
$scope.toggle = function() {
$scope.stuff.id = $scope.stuff.id === 5 ? 8 : 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span x-ng-show="stuff && [1,2,5].includes(stuff.id)">{{stuff.name}}</span>
<button ng-click="toggle()">Toggle id between 5 and 8</button>
<pre>stuff.id = {{stuff.id}}</pre>
</div>
< IE11
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.stuff = {
id: 5,
name: 'foo'
}
$scope.toggle = function() {
$scope.stuff.id = $scope.stuff.id === 5 ? 8 : 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span x-ng-show="stuff && [1,2,5].indexOf(stuff.id) > -1">{{stuff.name}}</span>
<button ng-click="toggle()">Toggle id between 5 and 8</button>
<pre>stuff.id = {{stuff.id}}</pre>
</div>