Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element in angularjs analog of get by id in javascript?

Lets say I have button:

<button type="submit"
        value="Send" 
         id="btnStoreToDB"
         class="btn btn-primary start"             
         ng-click="storeDB()"
         ng-disabled="!storeDB_button_state"
         >
                <i class="icon-white icon-share-alt"></i>
                <span>Store to DB</span>
            </button> 

enter image description here

In JS to get this button I just do var btn = $('#btnStoreToDB'); and now can play with this button. So I can take it by id or class.

But how can I get this element with angularjs?

I want to add spinner to button during loading like showed here (Fiddle).

Since all my project I started to use angulajs only I try to do it wisely and do not like how do I know.

I thought to add: ng-model="btnStoreToDB" and use this:

  if($scope.btnStoreToDB){
      var spinner = new Spinner().spin();
      $scope.btnStoreToDB.appendChild(spinner.el);
  } 

but $scope.btnStartUpload is undefined. Suppose there is other way to fetch this button.

Please, help

like image 398
Maxim Shoustin Avatar asked Apr 21 '13 18:04

Maxim Shoustin


1 Answers

This is a good question, and a very common situation.

The Angular way of doing this is to use ng-show, ng-hide or ng-class on or within your button.

One idea might be to use ng-class like so:

<button ng-class="{ useSpinner: btnStoreToDB }">...</button>

This will add the class useSpinner to the button when btnStoreToDB is true, and remove the class when btnStoreToDB is false.

Another way would be to use ng-show like this:

<button ...>
    <i class="icon-white icon-share-alt"></i>
    <span>Store to DB</span>
    <div class="spinner" ng-show="btnStoreToDb">...</div>
</button> 

Now your view and controller are separated, and you are doing things the Angular Way.

like image 135
exclsr Avatar answered Oct 12 '22 10:10

exclsr