【问题标题】:$watch in post link of compile not working编译后链接中的 $watch 不起作用
【发布时间】:2016-08-07 11:00:12
【问题描述】:

我正在尝试将$watch 应用于帖子链接功能中的属性。

我的代码是这样的:

compile: function(){
     return {
         post:function(scope,element){
             scope.$watch('scope.x', function(){
                console.log(scope.x);
            })  
         }
     }
}

它只在页面加载时执行一次。有什么我无法弄清楚的问题吗?

编辑:

我正在使用 angular gridster 在网格中显示各种图表。我的 index.html 看起来像:

<div gridster>
    <ul>
        <chart ng-repeat="chart in charts">
        </chart>
   </ul>
</div>

chart 是另一个带有视图的指令:

<li gridster-item row="grid_row" col="grid_col">

脚本文件包含:

module.directive('chart', ['',
    function() {
        return {
            restrict: 'E',
            scope: {
                  grid_col: '=col',
                  grid_row: '=row',
            },
            compile: function(element, attrs) {
                return {
                     post: function(scope, element, timeout) {
                         scope.$watch('grid_col', function() {
                         console.log(scope.grid_col);
                       })
                    }
                }
            }
        };
    }
]);

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-compile angularjs-watch


    【解决方案1】:

    您不应在提供给$watchstring 中提及scope 名称。

    scope.$watch('x', function(){
        console.log(scope.x);
    })
    

    $watch over scope 将放在$scope 内的 $$watchers 对象内,并根据每个摘要循环的范围评估每个字符串值。

    【讨论】:

    • 我试过这个,但没有用,它第一次工作,但之后控制台什么也没有打印出来。
    • @user3035998 你能给我一个plunkr吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多