In Angular SPA application, you would normally have the following codes in app.js
var app = angular.module('MyApp', ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider.when("/home", {
controller: "homeCtrl",
templateUrl: "app/views/home.html"
});
});
the HTML (home.html)
<form role="form" id="formHome">
<div>
HTML Elements Here...
</div>
</form>
And the homeCtrl:
'use strict';
app.controller('homeCtrl', ['$scope', '$location', function($scope, $location){
$scope.angularFn = function(obj){
// Do Some Stuff with obj.
}
function myTestFunction(){
// Call $scope.angularFn here.
var obj = {name: 'John', team: 'Nissan'};
$scope.angularFn(obj);
}
}]);
The above code obviously would error out as the $scope.angularFn goes undefined.
I've read somewhere that you need to get the element ID for which the controller is being used, and call the angular function from that. i.e.:
angular.element(document.getElementById('formHome')).scope().angularFn(obj);
But checking the console.log(angular.element(document.getElementById('formHome')).scope)
seems to point to the angular.js library, instead of the controller, hence, calling the angularFn function is also undefined.
So, how would you be able to call the controller function from within the plain old JS function?