Angular Material - $ mdDialog自定义模板 - ng-click for function in directive?

时间:2017-12-22 14:28:27

标签: javascript angularjs angularjs-directive angular-material

我在带有templateUrl属性的自定义指令中使用了$ mdDialog.show()来访问对话框本身的自定义模板,其中我包含了两个按钮; “取消”按钮和“确认”按钮。

对于其中的每一个,我添加了一个ng-click,调用'cancelLeaver()'和'confirmLeaver()'函数,我需要能够在指令中写入,但不知道我会怎么做做。

我尝试使用$ mdDialog.then()功能,但由于自定义视图模板中有按钮,因此无效。

如何从视图模板的ng-click属性中调用函数?这些属性是在单独的指令中编写的?

HTML:

<md-dialog ng-controller="mainController" style="min-width: 30vw">

<md-dialog-content>

    <h2 class="md-title">Confirm leaver status</h2>

</md-dialog-content>

<md-dialog-content class="minus-padding-top">

    <p>Enter employee's leave date below</p>

    <br>

    <md-input-container class="md-prompt-input-container">

        <input id="leaveDate" name="leaveDate" ng-model="employee.leaveDate" ng-init="employee.leaveDate = currentDate" aria-label="Leave Date" required>

    </md-input-container>

</md-dialog-content>

<md-dialog-actions>

    <md-button ng-click="cancelLeaver()">Cancel</md-button>

    <md-button ng-click="confirmLeaver()" ng-disabled="!employee.leaveDate.length">Confirm</md-button>

</md-dialog-actions>

</md-dialog>

指令:

app.directive('makeLeaver', function($window, $mdDialog, $mdToast, $timeout, $state) {
return {
    restrict: 'A',
    scope: {
        employee: '=',
    },
    controller: 'employeeDetailsController', 
    controllerAs: 'employeeDetails',
    bindToController: true,
    link: function(scope, element, attrs) {
        element.bind('click', function() {

            console.log('makeLeaver(' + '#' + scope.employee.id + ')');

            /* Show confirmation prompt dialog */
            $mdDialog.show({
                parent: angular.element('body'),
                clickOutsideToClose: true,
                templateUrl: 'views/employees/employeeDetails/dialogs/makeLeaver.html',
                targetEvent: element
            })

            /* ---------------- TRIED THIS BUT DIDN'T WORK ---------------- */
            scope.cancelLeaver = function() {
                console.log('cancelLeaver()');
                $mdDialog.hide();
            }

            scope.confirmLeaver = function() {
                console.log('confirmlLeaver()');
            }

        })
    }
}
})

1 个答案:

答案 0 :(得分:0)

你可以使用$ rootScope。$ broadcast(&#39; foo&#39;) 然后接收它,就像$ rootScope.on(&#39; foo&#39;)。 另一种方法是通过函数传递范围。 查看this tutorial