2015-12-31 30 views
0

我想知道$scope.reset();在控制器功能中的用途是什麼?復位似乎沒有這個代碼工作很好,但文件說,使用此代碼,我不明白爲什麼:Angular js中的重置按鈕實現

<body ng-app="myapp" ng-controller="resetController"> 
    <label>Enter name</label><input type="text" ng-model="name"/> 
    <label>Enter emailid</label><input type="text" ng-model="email"/> 
    <button ng-click="reset()">Reset</button> 
    <script> 
     angular.module("myapp",[]) 
     .controller("resetController", function($scope) 
     { 
      $scope.reset = function() 
      { 
       $scope.name = ""; 
       $scope.email = ""; 
      } 
      $scope.reset(); /* not sure why we need this */ 
     }); 
    </script> 
</body> 
+0

復位將清除輸入字段'name'和'email'綁定到 – pixelbits

+0

,但即使省略了來自控制器@pixelbits的代碼'$ scope.reset();',輸入字段也被清除。那麼它的目的是什麼? – user1928158

+0

你是對的,在這種情況下它是多餘的。 – pixelbits

回答

1

你問/* not sure why we need this */

$scope.reset = function(){ 
      $scope.name = ""; 
      $scope.email = ""; 
} 
$scope.reset(); /* not sure why we need this */ 

事實上,它調用函數reset()在第一時間控制器被實例化,所以,如果你有時間對這兩個輸入進行任何思考。在使用它們之前聲明域以避免控制器端出現「未定義」錯誤更好。在這種特殊情況下,它會改變什麼,但可能在他們做更多事情的例子中。

你可以嘗試把警報的功能裏面,就應該把它第一次運行,並每次你點擊復位()

$scope.reset = function(){ 
      alert("call to reset"); 
      $scope.name = ""; 
      $scope.email = ""; 
} 
+0

非常感謝。觸發警報()解釋了一切。 – user1928158

2
<body ng-app="myapp" ng-controller="resetController"> 
     <label>Enter name</label><input type="text" ng-model="name"/> 
     <label>Enter emailid</label><input type="text" ng-model="email"/> 
     <button ng-click="reset()">Reset</button> 
    <script> 
     angular.module("myapp",[]) 
     .controller("resetController", function($scope) 
     { 
      $scope.reset = function() 
      { 
       $scope.name = ""; 
       $scope.email = ""; 
      } 
      $scope.reset(); /* not sure why we need this */ 
     }); 
    </script> 
</body> 

這是你的代碼。現在看,你有ng-click="reset()"。這是在控制器內調用$ scope.reset方法,因此字段被清除。

至於你想知道:$scope.reset();/*不知道爲什麼我們需要這個*/

NO,你不需要這個,除非你是不是要求從您的視圖此方法。 $scope.reset()用於控制器內部,當您需要在頁面加載事件中調用方法時。

*我認爲$scope.reset()可用於清除第一次加載頁面時的字段。

+0

你是對的。向重置功能添加警報()可以證明您說的是什麼。乾杯。 – user1928158

0

嘗試這種方式

<body ng-app="myapp" ng-controller="resetController"> 
<label>Enter name</label><input type="text" ng-model="fromData.name"/> 
<label>Enter emailid</label><input type="text" ng-model="fromData.email"/> 
<button ng-click="reset()">Reset</button> 
<script> 
    angular.module("myapp",[]) 
    .controller("resetController", function($scope) 
    { 
     $scope.fromData = []; 


     $scope.reset = function() 
     { 
      $scope.fromData = []; 
     } 
    }); 
</script>