簡體   English   中英

如何使用javascript事件從angularjs指令范圍傳遞值

[英]How to pass value back from angularjs directive scope with javascript event

m trying to accomplish: I have jQuery plugin that I want to wrap to be an angular directive. And to do this i need to pass params to it, and the plugin have it own m trying to accomplish: I have jQuery plugin that I want to wrap to be an angular directive. And to do this i need to pass params to it, and the plugin have it own即使在我嘗試更改傳遞的值的情況下, m trying to accomplish: I have jQuery plugin that I want to wrap to be an angular directive. And to do this i need to pass params to it, and the plugin have it own onchange中,因此它將反映在原始范圍內。 而且我得到了一些非常意外和奇怪的結果。 這是小提琴:

http://jsfiddle.net/q1915b38/2/

在這里,我試圖模擬我想要完成的最小例子。 但正如你所看到的那樣根本不起作用。 原始控制器范圍中的值不會更改。 但在現實世界的例子中,它的行為有點不同。 這里是小提琴2號。

http://jsfiddle.net/ne5hbgxp/

我從第一個改變的唯一一件事就是來自模板的模板:

template: "<input type='text' id='blah' />",

template: "<input type='text' id='blah' ng-model='abc' />",

基本上我添加到模板的ng-model屬性,我根本不使用任何地方。 但它只是從完全不工作到使用故障。 現在當第一次改變觸發時沒有任何反應。 但是當它第二次觸發時 - 來自先前變化的值被傳遞到原始范圍。 當我改變3時間值時 - 第二次的值轉到控制器。 等等。 所以基本上它有一個延遲,退步一步為我不明原因。 這是我在我的真實世界示例中面臨的確切行為,盡管根本沒有ng-model ,所有內容都是通過jQuery插件生成的。

基本上我的問題如下:

1)為什么它不在第一個例子中工作

2)為什么它在第二個例子中使用這個奇怪的行為,一步延遲? 這種行為的邏輯是什么?

3)解決這個問題的正確方法是什么?

由於您使用jQuery更新指令中的某些內容,因此需要調用$apply()來觸發角度摘要周期

link: function(scope, iElement, iAttrs, controller) {
    $('#blah').change(function() {
        scope.value = $(this).val();
        scope.$apply();
    });
}

JSFiddle鏈接

然而,仔細觀察這一點,是否有理由在此示例中更喜歡jQuery .change() Angular提供了ngChange ,這可能就是你正在尋找的東西,因為你可以減輕顯式調用摘要周期,因為我們處於Angular世界而不是與jQuery作斗爭。 一個例子可能包括......

<input type='text' id='blah' ng-model='abc' ng-change='update()'/>

scope.update = function() {
    scope.value = scope.abc;
}

JSFiddle鏈接ng-change

問題很簡單...更改范圍超出angular的核心指令的事件對於角度是不可見的,因此您需要通知angular執行摘要以便可以更新視圖。

這是通過$apply()完成的,或者可以使用$timeout()來防止在另一個摘要周期正在進行時調用$apply()

    link: function (scope, iElement, iAttrs, controller) {
        $('#blah').change(function () {
            var $el =$(this);
            scope.$apply(function () {
                scope.value = $el.val();
            })
        });
    }

我建議利用指令中公開的iElement 當jQuery包含在angular之前的頁面中時,這是一個jQuery對象

暫無
暫無

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

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