AngularJS - Remove/Add Class on element based off if element is active/hover/or contains a value

Viewed 37

I have a magnifying glass that when you hover or click on it, it expands to a full search bar. I want the functionality to be that when the search bar is active, it will stay expanded until clicked off, or will stay expanded if the bar has a value. I have the logic in jQuery, but this is my first time using AngularJS (not Angular) and I do not know how to turn this jQuery into a directive, or if there is some built in functionality I am missing. Thank you!

jQuery("#inpt_search").on("focus", function () {
 jQuery(this).parent("label").addClass("active");
});

jQuery("#inpt_search").on("blur", function () {
 if (jQuery(this).val().length == 0)
   jQuery(this).parent("label").removeClass("active");
});
1 Answers

var myApp = angular.module('myApp', []);
// set for Home Controller
myApp.controller('HomeCtrl', function($scope) {
  $scope.blueClass = function() {
      $scope.class_name = "blue";
      $scope.multi_message ="Blue Class Added";
  };
});    
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<html>
  <head>
    <link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <script data-require="angular.js@1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  </head>

  <body ng-app="myApp">
    <div class="container" ng-controller="HomeCtrl">

      <div class="alert" ng-class="{blue:'bg-info', red:'bg-danger',green:'bg-success' }[class_name]">{{multi_message}}</div>

      <a class="btn btn-info" ng-click="blueClass()"> Blue Class</a>
    </div>
  </body>
</html>

Related