Reputation: 1
I have this code where I am expecting some data from the View/HTML but the variable $scope.cityName is undefined.
app.controller("citycontroller", function ($scope, cityfactory) {
$scope.searchByCid = function () {
console.log("Checking for city data");
var promise = cityfactory.serverCall($scope.cityName);
promise.then(function (data) {
$scope.result = data.data;
console.log($scope.result);
}, function (error) {
$scope.error = error;
});
};
console.log($scope.cityName);
});
Here is the HTML
<div>
<input type="text" ng-model="cityName" placeholder="Search places.." ng-init="cityName='Delhi'">
<button ng-click="searchByCid()" id="checkcity">Check</button>
</div>
Upvotes: 0
Views: 90
Reputation: 1462
console.log($scope.cityName);
This statement is outside the $scope.searchByCid function. When controller get loaded first time(While rendering html) then it is calling
console.log($scope.cityName);
Because of that it is showing undefined for $scope.cityName;
But you will be getting $scope.cityName in $scope.searchByCid because it is initialized using ng-init attribute.
Shift console.log inside your method.
Upvotes: 0
Reputation: 26
Create an object in your controller instead of using a single variable $scope.cityName
. Try to use something like $scope.data.cityName
, changing your ng-model
to data.cityName
. Also, try to initialize your variable in the beginning of your controller.
Upvotes: 0
Reputation: 15290
console.log($scope.cityName);
This statement is not part of any change event handler or function that digestion cycle to cause run.
Your cityName
is changing.If you want check it in JS :
$scope.callMe = function(){
console.log($scope.cityName);
}
HTML :
Use ngChange
<input type="text" ng-model="cityName" placeholder="Search places.." ng-init="cityName='Delhi'" ng-change="callMe()">
OR Simply check in html using interploation
:
<span>{{cityName}} </span>
OR
use $scope.$watch
in JS.
$scope.$watch('cityName',function(oldVal,newVal){
console.log(newVal); //it will print new updated cityname
})
Upvotes: 1