简体   繁体   中英

Use angularjs function return in javascript

I have a angularJS function which returns a value and would like to create an if statement in javascript. I've tried the following but so far no luck.

AngularJS:

            $scope.orderTotal = function(index) {
                    var orderTotal = 0;
                    angular.forEach($localStorage.items, function(items) {
                        orderTotal += items.quantity;
                    })
                    return orderTotal;
            };

Javascriptfile.js:

jQuery(document).ready(function() {
  document.write(orderTotal());
}

or:

if (orderTotal() > 10) { 
  document.write(orderTotal());
}

Is it possible to do something like this and what would it look like?

RvdM - "Because adding and removing classes on divs is something I do with javascript I need to have some variables defined in angularjs available in javascript. Are there better ways to accomplish this? "

Yes, to add and remove classes on elements in AngularJS, use the ng-class directive.

From the Docs:

ngClass

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

-- AngularJS ng-class Directive API Reference .

You can - I'd question why, but oh well. You can use angular.element and .scope to get the current scope your function is contained in.

For example, say your above function was inside the controller MyController

<div id="controller" ng-controller="MyController"></div>

The JS you'd use is:

var scope = angular.element(document.getElementById("controller")).scope();

scope now has access to all scope methods:

var total = scope.orderTotal();

the DOM :

<div id="mycontroller" ng-controller="mycontroller"></div>

In jquery you do this and it will access that controller and call that function

var orderTotal;
 $('#mycontroller').load = function(){
     orderTotal = angular.element('#mycontroller').scope().orderTotal();
 }  

If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed
Here you go :)

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