2

I wrote a Module to keep track of all my helper functions (scripts/apps.js):

angular.module('app', ['ngResource']).run(function($scope){

$scope.UTIL = {

setup_pod_variables: function (pods){...}
...

});

I'm trying to call the helper function from my Controller defined in another directory: scripts/controller/Dashboard.js:

scope.UTIL.setup_pod_variables(pods);

I have included the other module:

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

But it seems that I am still getting an error:

TypeError: Cannot read property 'setup_pod_variables' of undefined
at new <anonymous> (file:///Users/simon_zhu/Documents/nautilus/app/scripts/controllers/Dashboard.js:16:12)
at d (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:30:346)
at Object.instantiate (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:30:475)
at file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:61:228
at file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:48:320
at q (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:7:380)
at W (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:48:186)
at f (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:42:268)
at f (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:42:285)
at f (file:///Users/simon_zhu/Documents/nautilus/app/scripts/angular.min.js:42:285) 

Any Ideas?

2 Answers 2

1

Utility functions and data is better placed in a service, then it can be accessed from anywhere.

Your problem is that $scope in the module is not the same as the $scope in your controller.

The service solution would look something like this (might contain some errors as it is written from my head and not tested)

angular.module('app',[]).factory('utils', function(){
  return { setup_pod_variables: function(pods){...}};      
}

angular.module('app').controller('myController', ['utils', function(utils){
  utils.setup_pod_variables(...);  
}])
Sign up to request clarification or add additional context in comments.

Comments

0

Hi this function should be define in $rootScope rather than controller(DashBoard.js) local $scope, then only you can utilize it in other controllers.

Just make it $rootScope.UTIL.setup_pod_variables(pods){} in DashBoard.js then you invoke same function in another controller then it should work.

Or alternate solution is that you can make it in angular service if it is performing some business logic or if your requirement is to use at another place or if your system in future will evolve like this.

Comments

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.