简体   繁体   中英

How to add class on a button click in Angular JS

I have a form with fields which are disabled by default. User can only view the info in it unless they press the edit button. when they click the edit button the fields will be re enable the fields with some new styles(say a green border) i want to add a class to these field which i can style in my CSS. What is the Angular way to do it?

HTML

  <form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
    <div class="form-group">
      <label>Name</label>
      <div class="col-sm-6">
        <input type="text" class="form-control" ng-model="name" ng-disabled="true">
      </div>
    </div>
    <div class="form-group">
      <label>Email</label>
      <div class="col-sm-6">
        <input type="email" class="form-control" ng-model="email" required ng-disabled="true">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-8 col-sm-6">
        <button type="submit" class="btn btn-success">Edit</button>
      </div>
    </div>
  </form>

Controller

  function ExchangeController($scope) {
      var details = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
      $http.get(details).success(function(response){
          $scope.exchange_dt.exchange_name = response.name;
          $scope.exchange_dt.exchange_host_name = response.email;   
      });

      $scope.edit_exchange_setting_click = (function(){
        // add new class for the fields here dynamically        
      });
  }

You can use the ngClass directive for that ( documentation of ngClass )

If you want to add, let's say, green borders to your input element when the form is in the editable state , you will use ngClass as the following :

<input type="text" ng-class="{'greenBorder': editable}" ng-model="name" />

This will add the greenBorder css class only if the boolean variable editable is truthy. I simply defined greenBorder for the example as follows :

.greenBorder {
    border: 1px solid green;
}

Note that ngClass will not remove your existing classes, if any, added with class="..." . It will just append or not the class greenBorder to them. Therefore, there is absolutely no problem if you have a form-control or any other class added statically.

You can see a demo of that in action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM