如何通过指令参数将函数附加到对象?

How to attach functions to objects through directive parameters?

假设我想创建 dialogBox 指令。我想要一些对象来控制此对话框的行为。

为什么我不能将 open() 函数附加到 $scope.directiveHandle?为什么 $scope.directiveHandle.open 不存在于 ctrl 控制器中?

angular.module('app', [])
.directive('dialogBox', function(){
    return {
        restrict: 'E',
        replace: true,
        template: '<div>{{ handle.text }}</div>',
        scope: {
            handle: '='
        },
        controller: function($scope){
            $scope.handle.open = function(){
                console.log('Open is executed');
            };
        }
    };
})
.controller('ctrl', function($scope){
    $scope.directiveHandle = {
        text: 'it\'s working'
    };
    console.log('Is open() attached?', $scope.directiveHandle.open);
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<body ng-app="app">
    <div ng-controller="ctrl">
        <h3>This is my directive</h3>
        <dialog-box handle="directiveHandle"></dialog-box>
    </div>
</body>

您可以使用该 directiveHandle 对象从控制器调用您想要的任何功能。检查工作演示:DEMO

您放置 console.log 指令的位置尚未初始化,因此尚未附加函数。