我正在尝试使用ng-repeat
和limitTo
编写一些应用程序,但似乎输入字段和按钮无法在同一模型值上一起工作。
问题是,一旦我从input field
更改了值,buttons
将不再有效。你能告诉我为什么吗?
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>
答案 0 :(得分: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--;
}
});
&#13;
<!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>
&#13;
答案 1 :(得分:1)
这是因为你直接在ng-model中绑定了值。把它放在一些对象中它会工作得很好。像这样:
<input type="number" ng-model="vm.counter">
https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes
错误#2:)