有没有一种方法来观看从属性的角度外部世界引起的变化? [英] Is there a way to watch attribute changes triggered from outside the angular world?

查看:148
本文介绍了有没有一种方法来观看从属性的角度外部世界引起的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解世界的角度和无棱角的世界之间的相互作用。

I’m trying to understand interactions between the angular world and the non-angular world.

由于一个声明这样的指令:

Given a directive that one declares like this:

<dir1 id="d1" attr1="100"/>

如果外角code改变指令是这样的:

If code outside angular changes the directive this way:

$("#d1").attr("attr1", 1000);

该指令如何才能知道它的属性之一发生了变化?

How can the directive know that one of its attribute has changed?

推荐答案

这将是最好的,使该指令这里面的变化来代替。如果出于某种原因,这是不可能的,那么有几个选项。

It would be best to make this change inside the directive instead. If, for whatever reason, that's not possible, then there are a couple of options.

应用程序之外,获取到应用程序中的任何DOM元素的引用。使用引用,你就可以得到它的范围的参考。你可以用ID 使用元素D1 。例如:

Outside the app, get a reference to any DOM element within the app. Using that reference, you can then get a reference to its scope. You could use your element with id d1. For example:

var domElement = document.getElementById('d1');
var scope = angular.element(domElement).scope();

下面是几个选项:

修改,而不是进行直接切换到视图模型。在链接功能,初始属性值存储在一个范围的变量,如:

Modify the model instead of making a direct change to the view. In the link function, store the initial attribute value in a scope variable like:

scope.myvalue = attrs.attr1;

然后您可以更改喜欢的应用程序之外的值(使用上述参考范围):

Then you can change the value outside the app (using the above reference to scope) like:

scope.$apply(function(){
    scope.myvalue = 1000;
    console.log('attribute changed');
});

这里是一个小提琴

如果该视图使用jQuery直接操作,我不知道任何使用 $的观察 $观看或分离范围结合,将工作的属性,因为它们都绑定到该属性前pression本身,只有一次,当链路功能是第一次运行。更改该值将导致这些绑定失败。所以,你不得不 $观看的DOM元素本身的属性(通过,而不是 ATTRS

If the view is manipulated directly with jQuery, I don't know of any use of $observe, $watch, or an isolate scope binding to the attribute that will work, because they all bind to the attribute expression itself, just once, when the link function is first run. Changing the value will cause those bindings to fail. So you'd have to $watch the attribute on the DOM element itself (rather than through attrs):

scope.$watch(function(){         
    return $(el).attr('attr1');    // Set a watch on the actual DOM value
}, function(newVal){
    scope.message = newVal;
});

然后您可以更改喜欢的应用程序之外的值(使用上述参考范围):

Then you can change the value outside the app (using the above reference to scope) like:

scope.$apply(function(){
    $("#d1").attr("attr1",1000);
});

这里是一个小提琴

这篇关于有没有一种方法来观看从属性的角度外部世界引起的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆