简体   繁体   中英

JavaScript Function to AngularJS

I have been getting interested in Angular recently and I was trying it out but having a little bit of a difficulty.

I have this JavaScript function:

function toggle(target) {
            var curVal = document.getElementById(target).style.visibility;
            document.getElementById(target).style.visibility = (curVal === 'visible') ? 'hidden' : 'visible';
        };

It changes the value between visible and hidden on each click of the following button:

<button class="btn-info" onclick="toggle('theBox')" type="button">Toggle Box</button>

I am trying to do this same thing in Angular, just not sure how, as far as I understand Angular is the same as JavaScript in terms of the functions.. I just don't understand how to do this same operation using Angular.

With angular, you don't even need a javascript function for toggle:

Button:

<button ng-click="isShown = isShown ? false : true" type="button">Toggle Box</button>

"Box":

<div ng-show="isShown"></div>

Just read about "ng-click" and "ng-show" or "ng-if".

Angular is just a JavaScript library. You can use the same JavaScript you are already using, as long as you include the JavaScript file which has the function on the page you're calling this function from.

Depending on which version of angularJS you're looking at using, you can leverage the library.

In angular 1.x you can use the ng-click directive http://www.w3schools.com/angular/ng_ng-click.asp

In angular 2 you can use click in the template, have a look at the list of events: http://learnangular2.com/events/

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