从Angular,Link或Controller指令返回回调?

时间:2017-02-06 19:15:09

标签: javascript angularjs angular-directive

我想创建一个表指令,我想知道如何传递一个回调,例如:“调用一个不在Controller中的删除函数”,我想要使用参数作为回调传递,但是有一段时间我会用它来打我的脑袋。当我可以通过“链接”返回回调时,我无法返回值,而控制器则无法返回。

Imagem when I use link , but don't back values of callback

Image when I use Controller

  

查看DashBoard

<div crud-table options='vm.options' callback='vm.myCallBack(response)'></div>
  

Controller DashBoard

(function() {

    'use strict';

    angular
        .module('senhalivre')
        .controller('DashboardMikrotikCtrl', DashboardMikrotikCtrl);

    DashboardMikrotikCtrl.$inject = [];

    function DashboardMikrotikCtrl() {

        var vm = this;

        vm.myCallBack = myCallBack;

        vm.options = {
            enabled : true,
            msg : 'DashBoard',
            // Configs etc..... 
        }

        //////////////////

        function myCallBack(response){

            console.log('Callback !!! ');
            console.log(response);

        }

    }

})();
  

指令

(function() {

    'use strict';

    angular
        .module('senhalivre')
        .directive('crudTable', crudTable);

    crudTable.$inject = [];

    function crudTable() {

        var directive = {
            bindToController: true,
            controller: crudTableCtrl,
            templateUrl : './views/crud/crudTable.html',
            controllerAs: 'vm',
            link: link,
            restrict: 'EA',
            scope: {
                options : '=',
                callback : '&callback'
            }
        };

        return directive;

        ////////////////

        function link(scope, element, attrs, ctrl) {

            scope.vm.callback({test : 'something'});
            // Work

        }

    }

    crudTableCtrl.$inject = [];

    function crudTableCtrl() {

        var vm = this;

        vm.callback({test : 'something'});
        // :( 

    }

})();

1 个答案:

答案 0 :(得分:0)

调用回调函数时,需要在参数对象中提供属性“response”:

function link(scope, element, attrs, ctrl) {
 scope.vm.callback({response: 'some response text'});
}

function crudTableCtrl() {
    this.callback({response: 'something'});
}