【问题标题】:How to attach functions to objects through directive parameters?如何通过指令参数将函数附加到对象?
【发布时间】:2019-09-10 09:12:28
【问题描述】:

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

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

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>

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2017-09-08
      • 2015-05-29
      • 2023-01-06
      • 2013-07-19
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多