V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
hustlzp
V2EX  ›  JavaScript

[AngularJS 请教] 如何在 directive 中 watch 某 scope 上的所有属性的变化?

  •  
  •   hustlzp · 2014-02-23 21:35:59 +08:00 · 7682 次点击
    这是一个创建于 3685 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有这样一个需求,我需要写一个A类型的directive,监控当前DOM元素对应的scope上的属性变化。

    当然,如果事先知道了这个属性的名字(比如val),可以这样写:

    restrict: 'A',
    link: function (scope, element, attrs) {
    --scope.$watch('val', function() {
    ----// DOM操作
    --});
    }


    但是这样的话耦合太紧了,能否监控scope上的所有属性?而不需指定某属性的name?

    有一种方法就是将$watch方法中的listerner(第二个参数)当做watchExpression(第一个参数)传进去:

    restrict: 'A',
    link: function (scope, element, attrs) {
    --scope.$watch(function() {
    ----// DOM操作
    --});
    }

    但这样性能损耗相当大,每次$digest执行的时候都要执行好多遍DOM操作...

    大家遇到过这种情形没?求指点啊!
    2 条回复    1970-01-01 08:00:00 +08:00
    timonwong
        1
    timonwong  
       2014-02-23 22:19:11 +08:00
    scope.$watch(function() {
    return [attrs.name1, attrs.name2, ...]; // Return an array of attribute names here, or get keys directly from attrs
    }, function() {
    // action, DOM 操作
    });
    hustlzp
        2
    hustlzp  
    OP
       2014-02-23 22:29:15 +08:00
    @timonwong Thanks!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3240 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:12 · PVG 20:12 · LAX 05:12 · JFK 08:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.