我試圖用ng-repeat
和limitTo
來編寫一些應用程序,但似乎輸入欄和按鈕不能在同一個模型值上一起工作。
問題是,一旦我改變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>
正是我想要的,謝謝! :) –
但請記住@Olezt其實是對的!堅持使用「控制器爲」語法,因爲它在很多方面都有幫助。最明顯的一點是可以順利地爲您的控制器使用ES6類,併爲它們使用繼承。那不整齊? –
是的,「控制器爲」語法是一個更好的解決方案,因爲「常見錯誤#3:不使用controllerAs語法」和「常見錯誤#4:未充分利用指定的controllerAs語法」。 –