2017-06-05 16 views
2

我試圖用ng-repeatlimitTo來編寫一些應用程序,但似乎輸入欄和按鈕不能在同一個模型值上一起工作。
問題是,一旦我改變input field的值,buttons將不再起作用。你能告訴我爲什麼嗎?如何使用angularjs數據綁定將一個模型變量連接到多個html元素?

angular.module('myApp', []).controller('namesCtrl', function($scope) { 
 
    $scope.names = [ 
 
     'Jani', 
 
     'Carl', 
 
     'Margareth', 
 
     'Hege', 
 
     'Joe', 
 
     'Gustav', 
 
     'Birgit', 
 
     'Mary', 
 
     'Kai' 
 
    ]; 
 
    $scope.test = 3; 
 
    $scope.dPlus = function(){ 
 
     $scope.test++; 
 
    } 
 
    $scope.dMinus = function(){ 
 
     $scope.test--; 
 
    } 
 
    
 
});
<!DOCTYPE html> 
 
<html> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
<body ng-app="myApp" ng-controller="namesCtrl"> 
 

 
<div ng-if='true'> 
 

 
<p>Type a number in the input field:</p> 
 

 
<p><input type="number" ng-model="test"></p> 
 
<input type="button" value="+" ng-click="dPlus()"/> 
 
<input type="button" value="-" ng-click="dMinus()"/> 
 
<div>{{ test }}</div> 
 

 
<ul> 
 
    <li ng-repeat="x in names | limitTo:test"> 
 
    {{ x }} 
 
    </li> 
 
</ul> 
 

 
</div> 
 

 

 
</body> 
 
</html>

回答

1

這是因爲你直接在NG-模型綁定值。把它放在一些物體上,它會工作得很好。就像這樣:

<input type="number" ng-model="vm.counter"> 

https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes

錯誤#2 :)

+0

正是我想要的,謝謝! :) –

+0

但請記住@Olezt其實是對的!堅持使用「控制器爲」語法,因爲它在很多方面都有幫助。最明顯的一點是可以順利地爲您的控制器使用ES6類,併爲它們使用繼承。那不整齊? –

+0

是的,「控制器爲」語法是一個更好的解決方案,因爲「常見錯誤#3:不使用controllerAs語法」和「常見錯誤#4:未充分利用指定的controllerAs語法」。 –

2

您應該使用controller as語法和它的作品。

如果模型是原始模型,子範圍將只創建一個新的模型 。但是,如果更改的是模型對象的屬性,則在父範圍上查找 將查找引用的對象並更改它的實際屬性 。 Common Mistake #2: Not Having a Dot In There


這裏是工作代碼:

angular.module('myApp', []).controller('namesCtrl', function() { 
 

 
var vm = this; 
 
    
 
vm.names = [ 
 
     'Jani', 
 
     'Carl', 
 
     'Margareth', 
 
     'Hege', 
 
     'Joe', 
 
     'Gustav', 
 
     'Birgit', 
 
     'Mary', 
 
     'Kai' 
 
    ]; 
 
    vm.test = 3; 
 

 

 
    vm.dPlus = function(){ 
 
     vm.test++; 
 
    } 
 
    vm.dMinus = function(){ 
 
     vm.test--; 
 
    } 
 
    
 
});
<!DOCTYPE html> 
 
<html> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
<body ng-app="myApp" ng-controller="namesCtrl as vm"> 
 

 
<div ng-if='true'> 
 

 
<p>Type a number in the input field:</p> 
 

 
<p><input type="number" ng-model="vm.test"></p> 
 
<input type="button" value="+" ng-click="vm.dPlus()"/> 
 
<input type="button" value="-" ng-click="vm.dMinus()"/> 
 
<div>{{ vm.test }}</div> 
 

 
<ul> 
 
    <li ng-repeat="x in vm.names | limitTo:vm.test"> 
 
    {{ x }} 
 
    </li> 
 
</ul> 
 

 
</div> 
 

 
<p>The list will only consists of names matching the filter.</p> 
 

 
</body> 
 
</html>

相關問題