有没有办法查看从AngularJS世界外部触发的属性更改? [英] Is there a way to watch attribute changes triggered from outside the AngularJS world?

查看:83
本文介绍了有没有办法查看从AngularJS世界外部触发的属性更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Angular世界和非Angular世界之间的互动。

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"/>

如果超出角度的代码以这种方式更改了指令,则:

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,我不知道对 $ observe $ watch 的任何使用,或与属性将起作用,因为在链接函数首次运行时,它们都绑定到了属性表达式本身,仅一次。更改值将导致这些绑定失败。因此,您必须 $ watch 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);
});

这是一个小提琴

这篇关于有没有办法查看从AngularJS世界外部触发的属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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