更新在ng-repeat内呈现的指令中的Controller $ scope属性

时间:2014-06-24 04:37:42

标签: javascript angularjs

我创造了一个小提琴(这是我的第一个,所以开始时非常头疼!):http://jsfiddle.net/rmN59/17/

<div ng-controller="MainCtrl">

<div ng-repeat='d in data'>
    <div id="container-{{ d.key }}">
        <h3>My text {{ d.key }}</h3>
    </div>

    <div class='myDirective' overlay-contents='$parent.overlayContents' name='container-{{ d.key }}'></div>
</div>
<div id="overlay" class="hidden" ng-click="hideOverlay($event)">
    <div ng-bind-html='overlayContents'></div>
</div>

    var myApp = angular.module('myApp',[]);

myApp.controller('MainCtrl', ['$scope', function ($scope) {
    var overlaySelector = '#overlay';
    var showOverlay = function(){
        $(overlaySelector).toggleClass('hidden');
    };

    $scope.data = [{ key: '1' }, { key: '2' }];

    $scope.overlayContents = 'alex';

    $scope.$watch('overlayContents', function(newVal, oldVal){
        if(newVal !== oldVal){
            showOverlay();
        }
    });

    $scope.hideOverlay = function(e){
        var target = $(e.target);

        if(target.is(overlaySelector)){
            target.toggleClass('hidden');
        };

        e.stopPropagation();
    };
}]);


myApp.directive('myDirective', ['$sce', function($sce){
    return {
        scope: {
            overlayContents: '=',
            container: '@name'
        },
        template: '<button>Click</button>',
        restrict: 'C',
        link: function(scope, element){
            var stripAngularProps = function(html){
                return html.replace(/ng-(scope|binding|bind-html="[\w\(\)\.\[\]]+")/g,'');
            };

            element.click(function(e){
                var container = $('#' + scope.container);

                if($(e.target).is(element.find('button'))){
                    var html = stripAngularProps(container.html());

                    scope.$apply(function(){
                        scope.overlayContents = $sce.trustAsHtml(html);
                    });
                }
            });
        }
    }
}]);

我有需要迭代的数据并为每次迭代创建一个指令。然后我在循环之外有一个覆盖指令,它将监听控制器上模型的更改(overlayContents)。此时,控制器将显示带有更新内容的叠加层。

控制器中的$ scope。$ watch永远不会触发。

更新:它适用于小提琴!烦人。我能看到的唯一区别是,我在这里使用虚拟数据,在我的实际项目中,我使用单独的文件作为模板。我已经拉了几个小时我留下的头发了!

更新2:overlayContents属性得到更新,它会反映在DOM中,但不会调用$ watch。

1 个答案:

答案 0 :(得分:0)

我自己修好了。很抱歉无法提供更具体的代码。

通过删除控制器中的DOM操作并将其移动到覆盖指令中,该指令监视overlayContents的更改,这似乎有效。也许是因为$ watch被添加到编译阶段之后的链接函数中。我仍然对Angular的工作方式有所了解。