0

We are developing with angularjs and are running against a problem

We are changing views from inside the controllers normally, but in this case we need to change the view from an other js file.

What is the best way to tackle this?

We have created a method:

toShop: function() {
   var e = document.getElementById('appContainer');
        var scope = angular.element(e).scope();
        scope.$apply(function() {
            scope.toShop();
        }); 
    }

But this isn't working, the scope object is defined, but the apply function is not working.

Is there another way in angular to change views from outside the controller?

edit, controller code:

controllers.controller('HomeCtrl', function($scope, $location) {
    $scope.toShop = function() {
        alert('ruN!');
        $location.url('/shop');
    };
});

The first js should run the method of the second js

barry007
  • 539
  • 1
  • 4
  • 14

1 Answers1

0

So you got the famous apply already in progress error when you did $apply

best approach iv'e seen til this version of angular is to use $timeout which check if the apply is already running. (source)

var app = angular.module('app', []);

app.controller('myCtrl',function($scope, $location, $timeout) {

   $scope.toShop = function() {
      alert('ruN!');
      $location.url('/shop');
    };

    $scope.toShopExternal = function() {
      $timeout($scope.toShop);
    };
  }
);

your external code

  <script>
    $(function() {
      $("#jquery-button").click(function() {
        var e = document.getElementById('appContainer');
        var scope = angular.element(e).scope();
        scope.toShopExternal();
      });
    });
  </script>

http://plnkr.co/edit/opMH6jc0Ya1hKfSnsx7c?p=preview

Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129