简体   繁体   中英

Calling an AngularJS controller function from outside of it

I have the following code:

app.controller('MatrixExpertCtrl', function($scope,$http){
    $scope.PassedMatrix=[];
   $scope.GetMatrixFromServer=function(){
        $http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
            alert("The matrix grabbed from the server is: " + resp[0].ans);
            $scope.PassedMatrix.push(resp[0].ans);
        });
    };

    $scope.DispSize=function(){
        alert("testing");
      alert("The size is "+$scope.PassedMatrix[0].size)  ;
    };
    //$scope.GetMatrixFromServer();
});

Now, suppose, in HTML, I have something like this:

    <div class="col-sm-3 col-md-3 col-lg-3">

              <div class="text-center">

                <h3>Example Survey</h3>

                <p>example paragrah</p>

                <p>More random text</p>

                <p>ending the paragraphs</p>

                  <button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>

              </div>

                //Much more code
<div id="body2">
          <div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">


      <div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">



          <div class="text-center">

Meaning with this:

Is it possible to call a function that is defined inside a controller, from outside of the scope of that same controller?

I need this because the function is manipulating a shared object, owned by the controller in a very very simple fashion (for example, clicking on the button changes the color of a given element).

I am having trouble to make this work, any help will be appreciated.

I think that declaring some data structures as global would help me solving this problem, but, I would like to avoid doing that because, besides it being bad practice, it might bring me more problems in the future.

If i understand your problem correctly than what you basically do have is one utility function which will work on your shared object and do your useful things (ie clicking on the button changes the color of a given element) and now you do require the same behaviour in another controller outside of it's scope. You can achieve the same thing in 2 different ways :

1).Create a service and make it available in your controllers like this :

<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
    return {
        changeColour: function() {
            alert("Changing the colour to green!");
        }
    };
});

myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,     
myService) {
    $scope.callChangeColour = function() {
        myService.changeColour();
    }
}]);
</script>
</head>
<body ng-controller="MainCtrl">
   <button ng-click="callChangeColour()">Call ChangeColour</button>
 </body>
</html>

Pros&Cons : More angularistic way, but overhead to add dependency in every different controllers and adding methods accordingly.

2).Access it via rootscope

<!doctype html>
<html ng-app="myApp">
<head>
 <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
 <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);

 myApp.run(function($rootScope) {
    $rootScope.globalChangeColour = function() {
        alert("Changing the colour to green!");
    };
 });

 myApp.controller('MainCtrl', ['$scope', function($scope){

 }]);
 </script>
 </head>
 <body ng-controller="MainCtrl">
    <button ng-click="globalChangeColour()">Call global changing colour</button>
 </body>
 </html>

Pros&Cons : In this way, all of your templates can call your method without having to pass it to the template from the controller. polluting Root scope if there are lots of such methods.

try removing semicolon

ng-click="DispSize()"

because it binds ng-click directive to the function.

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