Angularjs 数据绑定输入到列表元素的角度
我希望我的每个列表项都可以通过Angularjs 数据绑定输入到列表元素的角度,angularjs,Angularjs,我希望我的每个列表项都可以通过输入进行编辑。单击列表项将填充输入,但如何指定要更新的项?我的$watch正在工作 感谢您的帮助 我有一个小家伙: 代码如下: <body ng-app="myApp"> <div ng-controller="MyController"> <ul ng-repeat="item in collection"> <li ng-click="edit(item.name)">{{item.name
输入进行编辑。单击列表项将填充输入,但如何指定要更新的项?我的$watch
正在工作
感谢您的帮助
我有一个小家伙:
代码如下:
<body ng-app="myApp">
<div ng-controller="MyController">
<ul ng-repeat="item in collection">
<li ng-click="edit(item.name)">{{item.name}}</li>
</ul>
<input name="myinput" ng-model="myinput" />
</div>
</body>
您还需要将$index
传递到edit()
,以便知道以后要更新的数组索引:
var-app=angular.module('myApp',[])
.controller('MyController',函数($scope,$http){
$scope.collection=[
{name:'foo'},
{name:'bar'},
{名称:'foobar'},
{name:'barfoo'},
];
$scope.edit=函数(当前名称、当前索引){
$scope.myinput=当前名称;
$scope.myindex=当前索引;
}
$scope.$watch('myinput',函数(NewValue){
if($scope.myindex){
$scope.collection[$scope.myindex].name=NewValue;
}
})
})
- {{{item.name}
更改代码以执行此操作
<li ng-click="edit(item)">{{item.name}}</li>
最后回到你的标记中
<input name="myinput" ng-model="selectedItem.name" />
这样做的目的是将当前可编辑的项目切换到您单击的任何项目,然后当您单击它时,您在输入中键入的任何内容都将更新该项目。传递项目本身,而不是传递编辑(item.name)。然后angular将为您处理其余部分,不需要$watch或$index
<body ng-app="myApp">
<div ng-controller="MyController">
<ul ng-repeat="item in collection">
<li ng-click="edit(item)">{{item.name}}</li>
</ul>
<input name="myinput" ng-model="myinput.name" />
</div>
</body>
JS:
var app = angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
$scope.collection = [
{name:'foo'},
{name:'bar'},
{name:'foobar'},
{name:'barfoo'},
];
$scope.edit = function(current_item) {
$scope.myinput = current_name;
console.log(current_name);
}
})
- {{item.name}
JS:
var app=angular.module('myApp',[])
.controller('MyController',函数($scope,$http){
$scope.collection=[
{name:'foo'},
{name:'bar'},
{名称:'foobar'},
{name:'barfoo'},
];
$scope.edit=功能(当前项目){
$scope.myinput=当前名称;
console.log(当前_名称);
}
})
您没有正确更新代码。您仍在调用edit(item.name),它传递的是name属性,而不是项。
<input name="myinput" ng-model="selectedItem.name" />
<body ng-app="myApp">
<div ng-controller="MyController">
<ul ng-repeat="item in collection">
<li ng-click="edit(item)">{{item.name}}</li>
</ul>
<input name="myinput" ng-model="myinput.name" />
</div>
</body>
JS:
var app = angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
$scope.collection = [
{name:'foo'},
{name:'bar'},
{name:'foobar'},
{name:'barfoo'},
];
$scope.edit = function(current_item) {
$scope.myinput = current_name;
console.log(current_name);
}
})