使用AngularJS跟踪当前选定项目
我是AngularJS的新手,找不到合适的答案。我的应用程序当前包含通过Angular显示的项目列表。还有一个显示当前选定项目名称的标签,以及一个允许修改当前选定项目名称的输入框 我想不出的是如何同时:使用AngularJS跟踪当前选定项目,angularjs,Angularjs,我是AngularJS的新手,找不到合适的答案。我的应用程序当前包含通过Angular显示的项目列表。还有一个显示当前选定项目名称的标签,以及一个允许修改当前选定项目名称的输入框 我想不出的是如何同时: 允许选择项目,这将触发标签和输入框文本的更新,以显示新选择项目的名称 允许编辑输入框中的名称,该输入框将触发显示当前显示项目名称的标签的更新 对名称的编辑应反映在原始模型项中 目前,我正试图通过一个标记来跟踪哪个项目是最新的,但这并不是我想要的。理想情况下,我会用isCurrent=true直接
isCurrent=true
直接引用items
中的项目来替换下面的currentItem
当前项目名称标签:
`<div id="CurrentItem" data-ng-model="currentItem">{{currentItem.name}}</div>`
任何建议,谢谢 我不确定您当前的代码 JS
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'test' }
];
$scope.editing = null;
$scope.editItem = function(item) {
$scope.editing = item;
}
});
还有标记
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item.name}}
<a ng-click="editItem(item);">edit</a>
</li>
</ul>
<div ng-show="editing">
<input type="text" ng-model="editing.name"/>
<span>{{editing.name}}</span>
</div>
</body>
-
{{item.name}
编辑
{{editing.name}
希望这能有所帮助。如果您需要更多描述,请告诉我。太好了,谢谢。这表明,当你不知道自己在做什么的时候,很容易把事情复杂化!
var CoreAppController = function($scope, $location) {
$scope.changeItem = function(item) {
var length = $scope.items.length;
while(length-- ) {
$scope.items[length].isCurrent = false;
}
$scope.currentItem = item;
$scope.items.indexOf(item).isCurrent = false;
}
$scope.createItem = function(name, layout) {
$scope.items.push({ id: $scope.items.length + 1,
name: name,
isCurrent: false
});
}
// Initialisation
$scope.items = [];
$scope.createItem("Item 1");
$scope.createItem("Item 2");
$scope.items[0].isCurrent = true;
$scope.currentItem = $scope.items[0];
}
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'test' }
];
$scope.editing = null;
$scope.editItem = function(item) {
$scope.editing = item;
}
});
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item.name}}
<a ng-click="editItem(item);">edit</a>
</li>
</ul>
<div ng-show="editing">
<input type="text" ng-model="editing.name"/>
<span>{{editing.name}}</span>
</div>
</body>