[英]How to apply ng-style on ng-click dynamically to selected item without using ng-class in angular
How to apply ng-style on ng-click dynamically without using ng-class in angular? 如何在不使用ng-class的情况下在ng-click上动态应用ng-style? something like changing color for selected active menu only. 就像只为选定的活动菜单更改颜色。 something like this DEMO but with ng-style. 像这样的演示,但具有ng样式。 Below is my code which is toggle function. 下面是我的代码,这是切换功能。 Can anyone solve this by changing the code or use your own example to change color or font-size for active item when clicked and rest of the items to default state. 任何人都可以通过更改代码来解决此问题,或者使用您自己的示例来更改活动项目的颜色或字体大小(单击时将其更改为其他状态,并将其余项目更改为默认状态)。
<div ng-style="x.selected && {'color':'white','font-weight':'bold'}"
ng-click="select(x)" ng-repeat="x in myData" ></div>
var app = angular.module('anApp', ['angular.filter']);
app.controller('aCtrl', function($scope) {
$scope.data = [
{
"id": 100,
"value": "2452"
},
{
"id": 100,
"value": "2458"
},
{
"id": 1,
"value": "2457"
},
{
"id": 1,
"value": "2459"
},
{
"id": 4,
"value": "2460"
},
{
"id": 5,
"value": "3458"
}
];
$scope.select = function(x){
x.selected = !x.selected;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
<div ng-style="x.selected && {'color':'red','font-weight':'bold'}"
ng-click="select(x)" ng-repeat="x in data" >
{{x.value}}
</div>
</div>
Try like this. 尝试这样。
var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.menuItems = ['Home', 'Contact', 'About', 'Other']; $scope.activeMenu = $scope.menuItems[0]; $scope.setActive = function(menuItem) { $scope.activeMenu = menuItem } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script> <div ng-app="plunker" ng-controller="MainCtrl"> <div class="account-item" ng-repeat='item in menuItems'> <div class="account-heading" ng-style="activeMenu === item && {'background' :'red' }"> <h4 class="account-title"> <a href="#/Messages" ng-click="setActive(item)"> {{ item }}</a> </h4> </div> </div> </div>
Can you try using $index as below example with plunker below, 您可以尝试使用以下示例中的$ index和下面的plunker,
http://plnkr.co/edit/Z977olOlajTNZENbqx7D?p=preview http://plnkr.co/edit/Z977olOlajTNZENbqx7D?p=preview
<div ng-repeat="x in data" ng-click="setSelected($index)" ng-style="$index === selectedId && {'background' :'red' }">
{{x.value}}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.