Ionic ngModel指令未更新控制器

时间:2015-05-03 16:09:08

标签: angularjs cordova angularjs-scope phonegap-plugins ionic

我定义了以下离子模板:

<ion-view view-title="Home" hide-nav-bar="true">
  <ion-content class="padding">
    <label class="item item-input">
       <input type="text" placeholder="Enter Name" ng-model="name">
    </label>
    <button class="ion-plus-circled button button-block button-positive" ng-click="add()" side="right">
      Add Name
    </button>
 </ion-content>
</ion-view>

我的控制器如下所示:

//home controller
.controller('HomeCtrl',['$scope','$log',
   function($scope,$log){
      $scope.name = null;
      $scope.add = function(){  
         var name = $scope.name;
         if(name != null && name != undefined){
            $log.debug('participant added to list:' + name);
         }else{
            //notify the user that they must enter a valid name
            $log.debug('user entered invalid name');
         }
    };
}])

add()上调用$scope时,$scope.name值为空。

因此,上面的代码和标记将导致记录以下内容。

user entered invalid name

为什么它不从文本框中提取值?

1 个答案:

答案 0 :(得分:1)

使用此代码:

<强> HTML

<button class="ion-plus-circled button button-block button-positive" ng-click="add(name)" side="right">
    Add Name
</button>

<强>控制器:

 $scope.add = function(name){  
         if(name != null && name != undefined){
            $log.debug('participant added to list:' + name);
         }else{
            //notify the user that they must enter a valid name
            $log.debug('user entered invalid name');
         }
    };

<强> HTML:

<input type="text" placeholder="Enter Name" ng-model="obj.name">

<强>控制器:

$scope.add = function(){  
         var name = $scope.obj.name;
         if(name != null && name != undefined){
            $log.debug('participant added to list:' + name);
         }else{
            //notify the user that they must enter a valid name
            $log.debug('user entered invalid name');
         }
    };