首页 > 解决方案 > 在指令的隔离范围内绑定的对象在范围结构中,但在访问时未定义

问题描述

HTML

<div class="block-area" id="basic" ng-controller="DocumentEditorController">
    <docs-hierarchy table-of-contents="document.toc" document-id="123123123">
    </docs-hierarchy>
</div>

指示

.directive('docsHierarchy', [function() {
    return {
        restrict: 'E',
        scope: {
            tableOfContents: '=',
            documentId: '@',
        },
        template: '' +
            '<docs-hierarchy-tree-render tree="tree"></docs-hierarchy-tree-render>' +
            '',
        link: function($scope, elem, attrs) {
            $scope.meta = {};
            $scope.tree = {};

            function parseTree() {
                console.log("TOC", "$scope:", $scope);
                console.log("TOC", "$scope.tableOfContents:", $scope.tableOfContents);
                console.log("TOC", "$scope.tree:", $scope.tree);
                console.log("TOC", "$scope.documentId:", $scope.documentId);
            }

            parseTree();
        }

结果: 在此处输入图像描述

简单地说,我不明白值输出中的值如何存在$scope,并立即成为undefined下一行。为什么我无法获得已经评估的这个值?

但我可以很好地抓住字符串绑定。


编辑 01

我设法弄清楚了这样做的第一种方式,如下所示:

.directive('docsHierarchy', [function() {
    return {
        restrict: 'E',
        scope: {
            tableOfContents: '=',
            documentId: '@',
        },
        template: '' +
            '<docs-hierarchy-tree-render tree="tree"></docs-hierarchy-tree-render>' +
            '',
        link: function($scope, elem, attrs) {
            $scope.meta = {};
            $scope.tree = {};

            function parseTree() {
                console.log($scope.toc);
            }

            $scope.$watch('tableOfContents', function(newVal, oldVal) {
                if(newVal !== oldVal) {
                    $scope.toc = newVal;
                    parseTree();
                }
            });
        }
    };
}])

我仍然不明白为什么我必须这样做,如果tableOfContents据说是数据绑定

标签: angularjsangularjs-directive

解决方案


推荐阅读