使用AngularJS跟踪当前选定的项目

jwe*_*est 10 angularjs

我是AngularJS的新手,找不到合适的答案.我的应用程序目前包含通过Angular显示的项目列表.还有一个标签显示当前所选项目的名称,还有一个输入框,允许修改当前所选项目的名称.

我无法弄清楚的是如何同时:

  1. 允许选择一个项目,该项目将触发更新标签和输入框文本以显示新选择项目的名称
  2. 允许在输入框中编辑名称,以触发更新显示当前显示的项目名称的标签
  3. 对名称的编辑应反映在原始模型项中

目前,我正试图通过一个标志对项目跟踪哪个项目是当前的,这不是我想要的.理想情况下我会取代currentItem在下面以直接引用该项目itemsisCurrent=true.

当前项目名称标签:

`<div id="CurrentItem" data-ng-model="currentItem">{{currentItem.name}}</div>`
Run Code Online (Sandbox Code Playgroud)

当前项目名称输入框:

`<input id="ItemName" type="text" data-ng-model="currentItem" value="{{currentItem.name}}" />`
Run Code Online (Sandbox Code Playgroud)

显示所有项目:

<div data-ng-repeat="item in items" data-ng-click="changeItem(item)">`
    <img src="images/ItemIcon.png">
<div>{{item.name}}</div>
Run Code Online (Sandbox Code Playgroud)

控制器:

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];

}
Run Code Online (Sandbox Code Playgroud)

任何建议赞赏!

Ben*_*esh 18

我不确定你当前的代码,但这里是一个模拟,它会显示你正在请求的内容.

JS

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { name: 'foo' },
    { name: 'bar' },
    { name: 'test' }
    ];
    $scope.editing = null;
    $scope.editItem = function(item) {
      $scope.editing = item;
    }
});
Run Code Online (Sandbox Code Playgroud)

和标记

  <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>
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助.如果您需要更多描述,请告诉我.

  • 那是完美的,谢谢.只是表明当你不知道自己在做什么时,它太容易过于复杂了! (5认同)