如何使用 AngularJS 和 AngularFire 存储对“活动元素”的引用

How to store a reference to the "active element" using AngularJS and AngularFire?

本文关键字:元素 活动 活动元素 引用 AngularJS 何使用 AngularFire 存储      更新时间:2023-09-26

>我有一个简单的笔记应用程序,可以在文本区域中显示笔记列表和活动的选定笔记。我希望能够在列表中选择一个注释并对其进行编辑。

在我的控制器中,我有一个"活动"变量,指向笔记列表中的项目。仅使用AngularJS就可以正常工作。如果我添加 AngularFire,每当我更改文本区域中的内容时,活动元素就不再连接。存储此活动引用是一个坏主意吗?

以下是控制器的相关部分:

var notesApp = angular.module('notesApp', ['firebase']);
function NotesCtrl($scope, angularFire) {
    var fireBaseUrl = new Firebase('https://mynotesapp.firebaseio.com/notes');
    $scope.notes = [];
    $scope.select = function (note) {
        $scope.active = note;
    };
    angularFire(fireBaseUrl, $scope, 'notes').then(function () {
        $scope.active = $scope.notes[0];
    });
}

和 HTML:

<ul>
  <li ng-repeat="note in notes" ng-class="{active: note == active}">
    <a href="#" ng-click="select(note)">{{ note.title }}</a>
  </li>
</ul>
<textarea ng-model="active.body"></textarea>

这里有一个完整的示例:http://jsfiddle.net/4zsMH/。

因此,当您将所选笔记复制到$scope.active.时。Firebase 绑定丢失。我已经稍微修改了您的代码,现在可以工作了。

http://jsfiddle.net/MXUxZ/

视图

<div ng-app="notesApp">
    <div class="container" ng-controller="NotesCtrl">
        <div class="row">
             <h1>Notes</h1>
            <ul class="note-list col-xs-3 nav nav-pills nav-stacked">
                <li ng-repeat="note in notes" ng-class="{active: selectedIndex == $index}"><a href="#" ng-click="select($index)">{{ note.title }}</a>
                </li>
                <li><a href="#" ng-click="addNote()">+ Add Note</a>
                </li>
            </ul>
            <div class="note-detail col-xs-9">
                <textarea rows="20" style="width:100%" ng-model="notes[selectedIndex].body"></textarea>
            </div>
        </div>
    </div>
</div>

控制器

var notesApp = angular.module('notesApp', ['firebase']);
function NotesCtrl($scope, angularFire) {
    var fireBaseUrl = new Firebase('https://notes6754.firebaseio.com/notes');
    $scope.notes = [];
    $scope.select = function (note) {
        $scope.selectedIndex = note;
    };
    $scope.addNote = function () {
        var title = prompt('Note Title');
        if (title) {
            var note = {
                title: title,
                body: 'Replace me'
            };
            $scope.notes.push(note);
            $scope.active = note;
        }
    };
    angularFire(fireBaseUrl, $scope, 'notes').then(function () {
        $scope.selectedIndex = 0;
    });
}