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?
You can use controllerAs
syntax. The convention is that you should not use $scope
in your controller to assign variables and functions to template.
Javascript
var app = angular.module('MyApp', ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider.when("/home", {
controller: "homeCtrl",
controllerAs: 'vm', // note this is added to route
templateUrl: "app/views/home.html"
});
});
'use strict';
app.controller('homeCtrl', ['$location', function($location){
// this will be equal to the controller and will be same as $scope
// using $scope is not recommended and should be used as follows
// quick google on why not to use scope will give you plenty of explanation
var vm = this;
vm.angularFn = function(obj){
// Do Some Stuff with obj.
}
function myTestFunction(){
var obj = {name: 'John', team: 'Nissan'};
vm.angularFn(obj);
}
}]);
Template:
Then you can access the function or variable from the controller using vm.variableName
or vm.FunctionName()
<form role="form" id="formHome">
<div ng-click="vm.angularFn(someobject)">
HTML Elements Here...
</div>
</form>
Why use controllerAs
over $scope
http://codetunnel.io/angularjs-controller-as-or-scope/
https://toddmotto.com/no-scope-soup-bind-to-controller-angularjs/