角度传递变量

Angular passing variables

本文关键字:变量      更新时间:2023-09-26

我正在尝试在控制器中的不同函数之间传递变量。这是我用来执行此操作的代码:

.HTML:

<table class="flat-table">
            <tr>
                <th>User</th>
                <th>Comment</th>
                <th>Date</th>
                <th>Controls</th>
            </tr>
            <tr ng-repeat="doc in guest.docs">
                <td>{{doc.value.user}}</td>
                <td>{{doc.value.comment}}</td>
                <td>{{doc.value.date}}</td>
                <td>
                    <img class="controls" src="styles/delete.png" ng-click="guest.delete(doc.id)" title="Delete">
                    <img class="controls" src="styles/edit.png" ng-click="guest.visible = true; guest.editBox(doc.id)" title="Edit">
                </td>
            </tr>
        </table>
        <div id="signCon">
            <form name="addForm" ng-submit="guest.add()">
                <textarea type="text" ng-model="guest.signature.comment" id="comment" placeholder="Enter a comment?!" required></textarea>
                <br/>
                <input type="submit" value="Sign!">
            </form>
        </div>
    </div>
    <div id="editCon" ng-show="guest.visible === true">
        <h1>Edit</h1>
        <p>Here you can alter your comment.</p>
        <form name="editForm" ng-submit="guest.submitEdit(guest.editBox.signature)">
            <textarea type="text" ng-model="guest.submitEdit.comment" required></textarea>
            <br/>
            <input type="submit" value="Edit!">
        </form>
    </div>

角:

this.editBox = function(id) {
            var that = this;
            this.id = id;
            this.signature = {};
            if(self.visible) {
                $http({
                    url: 'http://ip:5984/guestbook/' + this.id,
                    method: 'GET',
                    withCredentials: true,
                    headers: {
                        'Authorization': auth_hash(UserService.get().username, UserService.get().password)
                    }
                }).success(function(data, status, headers, config) {
                    that.signature = data;
                    console.log(that.signature);
                }).error(function(data, status, headers, config) {
                    console.log("error!")
                });
            };
        };
        this.submitEdit = function(signature){
            var self = this;
            this.comment = '';
            this.signature = signature;
            console.log(this.signature);
        };

这个想法是,当用户单击编辑图像时,会出现一个新窗口,他们能够输入新评论并重新提交。 窗口显示正确,我能够正确拉动对象。这是在尝试调用提交编辑函数时,它似乎没有通过签名变量。我这样做是否正确?

如果我

没记错的话,您不会创建一个持久存储属性的 editBox 的新实例,因此 guest.editBox.signature 仅在 editBox 函数运行时存在,它不会持久存在。

您可以做的是在 editBox 之外的范围内创建一个新变量,如下所示

this.signature = {};

然后在 editBox 中,您可以将签名对象分配给新创建的 this.signature。

在您的编辑表单中,您可以调用 ng-submit with

ng-submit="guest.submitEdit(guest.signature)"

如有必要,在 submitEdit 结束时,您可以将 this.signature 重置回空对象。

附言你不使用$scope有什么原因吗?