2016-07-07 2 views
0

新しい角度です。 button1をクリックすると2つのボタンがあり、その色は緑色から赤色に変わり、その後button2をクリックすると、button1の色は再び緑色に変わります。 ng-clickを使ってどうすればいいですか?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> 
 
\t <script type="text/javascript" src="app.js"></script> 
 

 
\t <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",[]); 
 
\t myApp.controller('testCtrl', function($scope){ 
 
\t \t $scope.chngcolor = functionn{ 
 
\t \t 
 
\t \t }; 
 
\t }); 
 

です。 j ?ここ

+0

[重複](http://stackoverflow.com/questions/20460369/adding-and- removed-classes-in-angularjs-using-ng-click) – Gintoki

答えて

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'; 
    }; 

ここ動的にng-classディレクティブを使用してcssクラスを追加しJSFiddle

+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> 
0

ありますクリックイベント。

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> 

Live Demo @ JSFiddle

関連する問題