2017-03-26 17 views
0

我有这个代码,我期待从视图/ HTML的一些数据,但变量$ scope.cityName是未定义的。

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); 
    }); 

下面是HTML

<div> 
      <input type="text" ng-model="cityName" placeholder="Search places.." ng-init="cityName='Delhi'"> 
      <button ng-click="searchByCid()" id="checkcity">Check</button> 
     </div> 
+0

是'$ scope.result'数据在您的控制台中正确吗? –

回答

1

console.log($scope.cityName);

这种说法是没有任何改变的事件处理函数,消化周期导致运行的一部分。

cityName是changing.If你要检查它的JS:

$scope.callMe = function(){ 
    console.log($scope.cityName); 
} 

HTML:

使用ngChange

<input type="text" ng-model="cityName" placeholder="Search places.." ng-init="cityName='Delhi'" ng-change="callMe()"> 

或者干脆在HTML中使用检查interploation

<span>{{cityName}} </span> 
在JS

OR

使用$scope.$watch

$scope.$watch('cityName',function(oldVal,newVal){ 

    console.log(newVal); //it will print new updated cityname 
}) 
0

在控制器中创建一个对象,而不是使用单个变量$scope.cityName。尝试使用$scope.data.cityName之类的东西,将ng-model更改为data.cityName。另外,尝试在控制器的开始初始化您的变量。

0
console.log($scope.cityName); 

该语句不在$ scope.searchByCid函数中。当控制器得到加载第一次(虽然呈现HTML),则调用

console.log($scope.cityName); 

因为它显示未定义$ scope.cityName的;

但是您将获得$ scope.searchByCid中的$ scope.cityName,因为它使用ng-init属性进行初始化。

在您的方法内移动console.log。