如何使用 ng-click 从另一个函数调用一个函数? [英] How to call a function from another function, with ng-click?

查看:27
本文介绍了如何使用 ng-click 从另一个函数调用一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 var vm = this;vm.dt_data = [];vm.item = {};vm.edit = 编辑;vm.dtOptions = DTOptionsBuilder.newOptions().withOption('initComplete', function() {$超时(功能(){$compile($('.dt-uikit .md-input'))($scope);})}).withPaginationType('full_numbers').withOption('createdRow', function (row, data, dataIndex) {$compile(angular.element(row).contents())($scope);}).withOption('ajax', {数据源:函数(json){json['画']=1json['recordsFiltered'] = json.records.lengthjson['recordsTotal'] =json.records.length控制台日志(json)返回 json.records;},url: 'http://localhost:808/sistemadrp/public/ws/usuarios',类型:'获取',})//.withDataProp('记录').withOption('处理', 真).withOption('serverSide', true);vm.dtColumns = [DTColumnBuilder.newColumn('id').withTitle('Id'),DTColumnBuilder.newColumn('usuario').withTitle('Usuario'),DTColumnBuilder.newColumn('nombre').withTitle('Nombre'),DTColumnBuilder.newColumn('email').withTitle('Email'),DTColumnBuilder.newColumn('telefono').withTitle('Telefono'),DTColumnBuilder.newColumn('estado').withTitle('Estado'),DTColumnBuilder.newColumn('created_at').withTitle('Creado'),DTColumnBuilder.newColumn(null).withTitle('Acciones').notSortable().renderWith(function(data,type,full){vm.item[data.id] = 数据;返回 '​​ <a href="#" data-uk-modal="{target:\'#modal_header_footer\'}" ng-click="showCase.edit(showCase.item[' + data.id + '])">'+' <i class="md-icon material-icons md-bg-light-blue-900 uk-text-contrast"></i></a>'+' <a href="#" data-uk-modal="{target:\'#modal_header_footer_eliminar\'}" ng-click="showCase.edit(showCase.item[' + data.id + '])">'+' <i class="md-icon material-icons md-bg-red-900 uk-text-contrast">&#xE872;</i></a>';})];

表格:

 

<table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" class="uk-table" cellspacing="0" width="100%"></table></div>

我在这里给出的答案是使用 $ compile 已经可以这样工作

.withOption('createdRow', function (row, data, dataIndex) {$compile(angular.element(row).contents())($scope);})

现在单击按钮时,我什至调用了一个模态,并命令对象使用 ng-model

感谢您的帮助,它运行良好.

解决方案

EDIT:添加了用于演示 $compile

  • 在 html 中只有一个 body 标签用于初始化应用程序和一个 div 用于初始化控制器.

  • foo 控制器中,两个链接被创建为简单的字符串,但分别使用两个ng-click,然后使用$compile 服务进行编译.然后将结果附加到 idparent 创建为 jQlite 对象的 div 中(这里很重要!),所以当链接单击它们 ng-click 上的函数被执行(见控制台).这意味着 AngularJS 正确解释了编译的 html.

重要:这与您的代码之间的区别可能在于您的 renderWith 只是将参数作为一个简单的 html 节点而不是 jQuery/jQlite 对象.如果是这种情况,你不能以这种方式做你想做的事情.您可能需要为此找到解决方法.例如:您可以为 DTColumnBuilder 返回的对象的结果设置一个选择器(即:id),然后 $compilehtml 节点与我在代码段中显示的方式相同.

原帖

您应该使用 $compile 服务.像这样修改你的函数:

function actionsHtml(data, type, full, meta){vm.usuario[data.id] = 数据;var html = ' <a href="#" data-uk-modal="{target:\'#modal_header_footer\'}" ng-click="showCase.edit(showCase.usuario[' + data.id + '])"><i class="md-icon material-icons md-bg-light-blue-900 uk-text-contrast"></i></a>'+' <a href="#" data-uk-modal="{target:\'#modal_header_footer_eliminar\'}"><i class="md-icon material-icons md-bg-red-900 uk-文本对比度">&#xE872;</i></a>';返回 $compile(angular.element(html))($scope);}

片段

angular.module('myapp', []).controller('foo', function($scope, $compile) {var html = "<a class='hand' ng-click='hello()'><strong>Hi</strong> <small>(点击我并查看控制台)</small></a>"+<br/><hr/>"+"<a class='hand' ng-click='goodby()'><strong>Goodby</strong> <small>(点击我并查看控制台)</small></a>";/** 重要的!!如果您不使用下面的 angular.element 语法,而是使用* 'document.getElementById('parent') = $compile(html)($scope)',例如,它会显示类似 '[object], [object]' 的内容*/angular.element(document.getElementById('parent')).append($compile(html)($scope));$scope.hello = function() {console.log("你好!")}$scope.goodby = function() {console.log("再见!")}});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><style type="text/css">.手 {光标:手;光标:指针;}</风格><body ng-app="myapp"><div ng-controller="foo"><div id="父级"></div>

 var vm = this;
            vm.dt_data = [];               
            vm.item = {};
            vm.edit = edit;
            vm.dtOptions = DTOptionsBuilder.newOptions()
                .withOption('initComplete', function() {
                    $timeout(function() {
                        $compile($('.dt-uikit .md-input'))($scope);
                    })
                })
                .withPaginationType('full_numbers')
                .withOption('createdRow', function (row, data, dataIndex) {
                    $compile(angular.element(row).contents())($scope);
                })
                .withOption('ajax', {
                    dataSrc: function(json) {
                        json['draw']=1
                        json['recordsFiltered'] = json.records.length                            
                        json['recordsTotal'] =json.records.length
                        console.log(json)
                        return json.records;
                      },
                    url: 'http://localhost:808/sistemadrp/public/ws/usuarios',
                    type: 'GET',
                })
                //.withDataProp('records')
                .withOption('processing', true)
                .withOption('serverSide', true);

            vm.dtColumns = [
              DTColumnBuilder.newColumn('id').withTitle('Id'),
              DTColumnBuilder.newColumn('usuario').withTitle('Usuario'),
              DTColumnBuilder.newColumn('nombre').withTitle('Nombre'),
              DTColumnBuilder.newColumn('email').withTitle('Email'),
              DTColumnBuilder.newColumn('telefono').withTitle('Telefono'),
              DTColumnBuilder.newColumn('estado').withTitle('Estado'),
              DTColumnBuilder.newColumn('created_at').withTitle('Creado'),
              DTColumnBuilder.newColumn(null).withTitle('Acciones').notSortable().renderWith(function(data,type,full){
                  vm.item[data.id] = data; 
                    return  ' <a href="#" data-uk-modal="{target:\'#modal_header_footer\'}" ng-click="showCase.edit(showCase.item[' + data.id + '])">'+
                            ' <i class="md-icon material-icons md-bg-light-blue-900 uk-text-contrast"></i></a>'+
                            ' <a href="#" data-uk-modal="{target:\'#modal_header_footer_eliminar\'}" ng-click="showCase.edit(showCase.item[' + data.id + '])">'+
                            ' <i class="md-icon material-icons md-bg-red-900 uk-text-contrast">&#xE872;</i></a>';
              })                    
          ];       

Table:

 <div class="md-card-content" ng-controller="dt_default as showCase">
            <table datatable="" dt-options="showCase.dtOptions"  dt-columns="showCase.dtColumns" class="uk-table" cellspacing="0" width="100%">
            </table></div>

With the answer I was given here to make use of $ compile already works this way

.withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })

Now when clicking the button I even call a modal and I command the object to make use of the ng-model

Thanks for the help, it works well.

解决方案

EDIT: Added snippet for demonstrating the usage of $compile

  • In the html there is only a body tag for initialising the app and a div for initialising the controller.

  • In foo controller, two link are created as simple strings but with two ng-click respectively and then compiled with the $compile service. The result of that is then appended to the div which id is parent created as jQlite object (important aspect here!), so when the links are clicked the functions on their ng-click are executed (see console). It means AngularJS as interpreted properly the compiled html.

IMPORTANT: The difference between this and your code may be that your renderWith just take the parameter as a simple html node and not a jQuery/jQlite object. If that's the case you can not do what you're trying to do this way. You probably will need to find a workaround for this. For example: you could set a selector (i.e.: an id) for the result of the object returned by the DTColumnBuilder and then $compile that html node the same way I show in the snippet.

Original post

You should use the $compile service. Modify your function like this:

function actionsHtml(data, type, full, meta){
        vm.usuario[data.id] = data; 
        var html = ' <a href="#" data-uk-modal="{target:\'#modal_header_footer\'}" ng-click="showCase.edit(showCase.usuario[' + data.id + '])"><i class="md-icon material-icons md-bg-light-blue-900 uk-text-contrast"></i></a>'+
               ' <a href="#" data-uk-modal="{target:\'#modal_header_footer_eliminar\'}"><i class="md-icon material-icons md-bg-red-900 uk-text-contrast">&#xE872;</i></a>';

  return $compile(angular.element(html))($scope);
}

Snippet

angular.module('myapp', [])
  .controller('foo', function($scope, $compile) {

    var html = "<a class='hand' ng-click='hello()'><strong>Hi</strong> <small>(Click Me and take a look at console)</small></a>" +
      "<br/> <hr/>" +
      "<a class='hand' ng-click='goodby()'><strong>Goodby</strong> <small>(Click Me and take a look at console)</small></a>";
    /*
     * important!! if you don't use the angular.element syntaxt below, and instead you just use
     * 'document.getElementById('parent') = $compile(html)($scope)', for instance, it will be shown something like '[object], [object]'
     */
    angular.element(document.getElementById('parent')).append($compile(html)($scope));

    $scope.hello = function() {
      console.log("Hi there!")
    }

    $scope.goodby = function() {
      console.log("Goodby!")
    }
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<style type="text/css">
  .hand {
    cursor: hand;
    cursor: pointer;
  }
</style>

<body ng-app="myapp">
  <div ng-controller="foo">

    <div id="parent"></div>

  </div>
</body>

这篇关于如何使用 ng-click 从另一个函数调用一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆