【问题标题】:Issues with ngModel BindingngModel 绑定的问题
【发布时间】:2015-08-27 06:43:05
【问题描述】:

我在 Angular 中遇到绑定问题。

HTML:

<div ng-controller="myCtrl">
    <li> Discount
      <input ng-change="update_amount()" type="number" ng-model="discount" />
    </li>
     <li> Other Charges
      <input ng-change="update_amount()" type="number" ng-model="others" />
     </li>
</div>

JS:

ng.module('app').controller('myCtrl', [
  '$scope',
  function ($scope) {
    $scope.removeRestaurantFromActiveCall = function () {
      $scope.updateActiveCall(function (call) {
        call.restaurant = null;
      });
    };

    $scope.showModal = false ;
    $scope.others = 0 ;
    $scope.discount = 0 ;


    $scope.update_amount = function () {
      console.log('Change called') ;


      console.log($scope.others) ;    // Always zero
      console.log($scope.discount) ;  // Always zero

      console.log($scope) ;  // Does not have the current value for my fields
      console.log(this) ; // Has current values for my field

      console.log($scope === this) ; // False
      console.log($scope == this) ;  // False

    }  ; }) ; 

我在this 中获得了我的字段的值,但在scope 中没有。甚至不确定this 在这里指的是什么。

我哪里出错了?

【问题讨论】:

  • 你确定上面的 sn-p 工作正常吗?您的控制器声明与标记不匹配。
  • 这里您的控制器名称是 myCtrl 并且您正在尝试访问另一个控制器上的属性 app.leftPane.restaurant
  • 我的错。控制器名称在实际代码中很好。只是想在这里缩短它。忘记在这两个地方进行更改
  • 为了简洁起见,这只是代码的一部分。实际代码没有语法错误。

标签: angularjs


【解决方案1】:

在这里检查它工作正常:--

 function MyController($scope) {

   $scope.removeRestaurantFromActiveCall = function() {
     $scope.updateActiveCall(function(call) {
       call.restaurant = null;
     });
   };

   $scope.showModal = false;
   $scope.others = 0;
   $scope.discount = 0;


   $scope.update_amount = function() {
     console.log('Change called');


     console.log($scope.others); // Always zero
     console.log($scope.discount); // Always zero

     console.log($scope); // Does not have the current value for my fields
     console.log(this); // Has current values for my field

     console.log($scope === this); // False
     console.log($scope == this); // False



   };
 };
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app ng-controller="MyController">
  <li>Discount
    <input ng-change="update_amount()" type="number" ng-model="discount" />
  </li>
  <li>Other Charges
    <input ng-change="update_amount()" type="number" ng-model="others" />
  </li>

  <p>{{"discount =" + discount}}</p>
  <p>{{"others =" + others}}</p>
</div>

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签