Diamondhead
Diamondhead

Reputation: 67

Calling angular JS from outside controller

My angular app code:

(function() {

     var app = angular.module('checkout', []);  
     app.controller('TabController', function(){
         this.tab2Done=0;
         this.setTab2Done= function(newValue){
              this.tab2Done = newValue;
         };
     });
})();

I want to call tab2Done from the JavaScript function(function name call). I found a solution on the internet and I tried that method but it's not working. This is the method that I tried:

The div which have has ng-controller="TabController" has id="yourControllerElementID"

This is my javascript function:

function call(){   
    alert();
    e=$('#yourControllerElementID');
    scope=angular.element(e).scope();  
    scope.$apply(function(){
        scope.setTab2Done(1);
    });
}

but I got an error:

at Scope.$eval at Scope.$apply

What have I done wrong?

Upvotes: 1

Views: 170

Answers (2)

I think you problem is that the method you are trying to call is NOT in your scope. It looks like you are using the "Controller as" syntax, judging by the fact that you are setting the method on "this" in the controller.

You could provide a plunker to your example, but let me try to fix your problem with this code:

function call(){   
  var element = angular.element('#yourControllerElementID');
  var controller = element.controller();
  var scope = element.scope();  
  scope.$apply(function(){
    controller.setTab2Done(1);
  });
}

Upvotes: 1

Shi Wei
Shi Wei

Reputation: 272

Not sure what you are asking but your code looks weird, try this! Maybe this might give you a clue :)

angular.module('checkout', []).
  controller('TabController', ['$scope', function ($scope) {
         $scope.tab2Done=0;


         var setTab2Done = function(newValue){
              $scope.tab2Done = newValue;
          }

         //to call the function through the scope
         // e.g. from your html <a href='javascript:void(0)' ng-click='call()'></a>
         $scope.call = function(){
             setTab2Done(1);
        }

        //call the function directly on this script
        setTab2Done(1);
     });

Upvotes: 0

Related Questions