我是棱角分明的新人。我有两个按钮,因为我将点击button1,因此它的颜色将从绿色变为红色,之后我将点击button2,因此button1颜色将再次变为绿色。如何使用ng-click进行操作?
我的index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<title></title>
</head>
<body ng-controller ="testCtrl" >
<button type="button" class="btn btn-default" ng-click="chngcolor()" >Chnage Color</button>
<button type="button" class="btn btn-default" ng-click="chcolor()" >Pre Color</button>
</body>
</html>
这是我的app.js
var myApp = angular.module("myApp",[]);
myApp.controller('testCtrl', function($scope){
$scope.chngcolor = functionn{
};
});
我应该在app.js中编写哪些代码?
答案 0 :(得分:1)
<button type="button" class="btn btn-default" ng-class="color" ng-click="color=red" ng-init="color=green">Chnage Color</button>
<button type="button" class="btn btn-default" ng-click="color=green" >Pre Color</button>
<style>
.green {
color: green;
}
.red {
color: red;
}
</style>
答案 1 :(得分:0)
以下是使用角度控制器并设置ng-style
<div ng-controller="MainController">
<button type="button" class="btn btn-default" ng-click="chngcolor()" ng-style="color">Change Color</button>
<button type="button" class="btn btn-default" ng-click="chcolor()">Pre Color</button>
</div>
控制器代码
// set default color
$scope.color = {'background-color': 'green'};
$scope.chngcolor = function() {
$scope.color = {'background-color': 'red'};
};
$scope.chcolor = function() {
$scope.color = {'background-color': 'green'};
// Shorter way to for the same result
// $scope.color.backgroundColor = 'green';
};
这是JSFiddle
答案 2 :(得分:0)
在点击事件中使用css
指令动态添加ng-class
类。
CSS:
.red-color {
background-color: red;
}
.green-color {
background-color: green;
}
<强> HTML:强>
<button type="button" class="btn btn-default" ng-class="color" ng-click="color='red-color'">Change Color</button>
<button type="button" class="btn btn-default" ng-click="color='green-color'">Pre Color</button>