将范围设置为 null 块 2 方式绑定 angular 指令

setting scope to null blocks 2 way binding angular directive

我创建了一个指令,当我将绑定范围变量 (textStyleOriginal) 设置为 null 时,我相信双向绑定会被破坏。解决这个问题的好方法是什么?

.directive('textStylePalette', function($log, toastr, _){
        return {
            restrict: 'E',
            templateUrl: 'app/palettes/text/text-style-palette.html',
            scope: {
                textStyleOriginal: '=textStyle'
            },
            link: textPaletteLinkFn
        };

        function textPaletteLinkFn(scope, elem, attr) {
            scope._ = _;
            scope.textStyle = null;

            // Used when closing the palette
            scope.deselectStyle = function() {
                // I BELIEVE THE PROBLEM IS THE NEXT LINE
                scope.textStyleOriginal = null;
                scope.textStyle = null;
            };

   ...
            // THIS WATCH STOPS WORKING.
            scope.$watch('textStyleOriginal', function(newVal, oldVal){
                $log.debug('n: ' + newVal + '|o: ' + oldVal );
                debugger;
                if (newVal && newVal !== oldVal) {
                    ...
                }
            });
}

绑定初始连接的html如下:

<text-style-palette ng-show="selectedStyle !== null" text-style="selectedStyle">
</text-style-palette>

在我提出问题几分钟后,我尝试了一些似乎有效的方法。留下这个问题来记录我的回答:

基本上是最简单的,'always make passed scope variables as part of an object'。

我做了一些更改,以便提供指令的外部 selectedStyle 成为对象的一部分。这是代码

<cm-text-style-palette ng-show="selections.selectedStyle !== null" text-style="selections.selectedStyle">
</cm-text-style-palette>

请注意,它是 selections.selectedStyle 而不仅仅是 selectedStyle。

这个问题与变量指向的工作方式有关。有关详细信息,此视频可能会有所帮助:https://egghead.io/lessons/angularjs-the-dot#/tab-transcript

祝你的项目好运!

我想我知道问题出在哪里了。

由于您有一个独立的作用域,因此您将从父作用域中设置 textStyleOriginal。这意味着如果您用值 null 覆盖它,那么您将失去对原始对象的引用。 例如。即使您在父范围内修改 textStyleOriginal,它也不会对您的指令产生任何影响,因为您已经丢失了对它的引用。