簡體   English   中英

隔離范圍變量在鏈接函數中變得未定義

[英]Isolate scope variable is getting undefined inside link function

我有一個指令,它接收一個數據對象和一個對其隔離范圍的函數。 在鏈接函數中,我聲明了一個在某個事件(按鈕單擊)中觸發的范圍方法。

問題是傳遞給上述方法的值可以在其中使用,但作用域變量仍未undefined

指示:

commentsModule.directive('commentsDirective', [ function() {
        return {
            restrict: 'E',
            templateUrl: '/alarm-viewer-comments-template.html',
            scope: {
                alarmComments: "=value",
                sendNewComment: "&sendNewComment"
            },
            link: function(scope, elems, attrs, ngModelCtrl) {
                scope.sendComment = function(data) {
                    console.log(scope.newComment);//this newComment variable is undefined
                    scope.sendNewComment(data);//data is correct
                    scope.newComment = '';
                };
            }
        }
    }
]);

在鏈接函數中,傳遞到scope.sendComment data可用,但scope.newComment undefined 模板:

<h4>Comments</h4>
<div ng-repeat="comment in alarmComments.comments">
    <p>{{comment.timestamp}} | <strong>{{comment.user}}</strong>: {{comment.commentType}} {{comment.comment}}</p>
</div>
<div ng-if="alarmComments.editPermission && alarmComments.isActiveAlarm">
    <form name="commentsForm" role="form"  track-form>
        <input type="text" ng-model="newComment" pattern="/.{1,}" maxlength="4" required ng-enter="sendComment(newComment)"/>
        <button type="button" class="btn btn-primary" ng-disabled="commentsForm.$invalid" ng-click="sendComment(newComment)">Send</button>
    </form>
</div>

用戶界面:

<comments-directive value="alarmComments" send-new-comment="addNewComment(comment)"></comments-directive>

有人可以幫我嗎...?

編輯:我要輸入注釋后清除輸入文本字段。

在指令范圍內,您還應該將newComment屬性與alarmComments一起alarmComments 像下面-

scope: {
    alarmComments: "=value",
    newComment: "=newComment",
    sendNewComment: "&sendNewComment"
},

調試此類問題的一種好方法是呈現范圍ID(scope。$ id)並驗證它們是否具有相同的ID。

您能否在鏈接期間驗證scope。$ id是什么並將其呈現在模板中?

<h4>Comments</h4>
<div ng-repeat="comment in alarmComments.comments">
<p>{{comment.timestamp}} | <strong>{{comment.user}}</strong>:   {{comment.commentType}} {{comment.comment}}</p>
</div>
 <div ng-if="alarmComments.editPermission && alarmComments.isActiveAlarm">
<form name="commentsForm" role="form"  track-form>
    <input type="text" ng-model="newComment" pattern="/.{1,}" maxlength="4" required ng-enter="sendComment(newComment)"/>
    <button type="button" class="btn btn-primary" ng-disabled="commentsForm.$invalid" ng-click="sendComment(newComment)">Send</button>
{{$id}}
</form>
</div>

有時,模板會創建自己的范圍,您可能必須在模板中使用$ parent.newComment。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM