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

查看:24
本文介绍了有没有办法观察从 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"/>

如果 angular 之外的代码以这种方式更改指令:

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天全站免登陆