0

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.

7
  • 1
    It's not "in the controller", it's on the scope. If the ng-click directive is in another scope, it doesn't have access to that function. Either use scopes differently, or use some other state-sharing mechanism like a service, or perhaps by triggering an event. Commented Sep 14, 2015 at 11:48
  • 1
    can you provide jsfiddle or plunkr with your problem? Commented Sep 14, 2015 at 11:52
  • 1
    I'll try to set up a simple plunkr Commented Sep 14, 2015 at 11:54
  • 1
    plnkr.co/edit/ZnE0MTNrH4gW0ISnZqXx?p=preview Here it is. What I want is, when I click on the button, it changes the color of the rectangle to green. Commented Sep 14, 2015 at 12:03
  • 1
    why just not put button inside ng-app? like here: plnkr.co/edit/aDVzQFO250VNLqrpUsEg?p=preview Commented Sep 14, 2015 at 12:08

2 Answers 2

3

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 (i.e. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

@BrunoOliveira enjoy coding :)
1

try removing semicolon

ng-click="DispSize()"

because it binds ng-click directive to the function.

1 Comment

this same as with semicolon, because expression wouldbe parsed anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.