0

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>
1
  • is $scope.result data correct in your console ? Commented Mar 26, 2017 at 17:50

3 Answers 3

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
 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.

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.