Your approach has a few issues that need to be addressed.
- It's recommended not to name your controller. Instead, use an anonymous function that takes the necessary modules as parameters, like
.controller(function($http){ //do something });
or .controller(['$http',function($http){ //do something }])
. This helps in avoiding variable reference loss when minifying your JS files.
- Within your controller, define the desired function with the required parameter, such as
$scope.sendAjax = function(city){ //do something }
. From your view, you can call this function with just the argument needed, like ng-submit="sendAjax(city)"
- Try to minimize the use of scope. As mentioned in the book AngularJS: Up and Running by Shyam Seshadri and Brad Green:
Prior to 1.2 version of AngularJS, $scope was injected into the controller, and variables like helloMsg and goodbyeMsg were set on it. But starting from AngularJS 1.2, there is a new syntax known as the controllerAs syntax which allows defining variables on the controller instance using the this keyword, and accessing them through the controller from HTML.
The advantage of this syntax over the older one is that it clearly indicates in the HTML which variable or function belongs to which controller and its instance. It eliminates the need to search for variables within the codebase, especially in complex, nested UIs. The controller instance is directly identifiable in the HTML.
To implement this, utilize the controller as syntax in your view:
"ng-controller="WeatherController as weather"
, then always refer to the alias to access Weather Controller scope, like
ng-submit="weather.sendAjax()"
.
In your controller, assign the function to this, for example
this.sendAjax = function(){ \\do something }
. It's good practice to assign
this to another variable to avoid it being overridden. You can initialize a variable as self in the beginning of your controller script like
var self=this
and continue referencing the controller as self onwards, e.g.,
self.sendAjax = function(){ \\do something }