-->

如何绑定NG单击插入指令嵌入HTML块内部的HTML块(How to bind ng-click t

2019-10-21 16:32发布

Plnkr: http://plnkr.co/edit/6xe46opL2kpgQrf7VaEu?p=preview

我有一个ng-click="switchCurreny()我试图得到工作被放置嵌入在页面上从我的HTML的另一个块内的HTML的块功能directive

我的app-main是放置HTML的另一块到指令放在HTML控制器,还包含了ng-click功能,我试图让工作:

var app = angular.module('app-main', ['ngAnimate', 'wallet-directives'])
.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {

    var vm = $scope;
    var currency = 'USD';
    vm.modal = false;
    vm.modal_send = false;
    vm.modalActive = false;

    // HTML to be placed inside of directive placed HTML in <wallet-modals>
    var send_html = '<div ng-click="switchCurreny()" class="btn_usd noselect">'+currency+'</div>';

    // Open the modal, then place send_html into modal_bind:
    vm.openModal = function($event) {
        vm.modal = true;                             // show modal
        vm.modal_send = true;                        // show modal_send 
        vm.modal_bind = $sce.trustAsHtml(send_html); // stick send_html inside of modal_bindd
    }

    vm.closeModal = function() {
        vm.modal = false;
        vm.modal_send = false;
    };

    // ng-click function inside of send_html:
    vm.switchCurreny = function() {
        console.log('clicked');
        if (currency === 'USD') {
            currency = 'BTC';
        } else {
            currency === 'USD';
        }
    };
}]);

我与HTML模式的指令

(function() {

    var app = angular.module('wallet-directives', [])
    .directive('walletModals', function () {

        return {
            restrict: 'E',
            template: '<div ng-show="modal_send" class="modal"><p>The Modal, button below:</p><br/><div ng-bind-html="modal_bind"></div></div>'
        };
    });

})();

HTML

<!-- Directive goes here -->
<wallet-modals></wallet-modals>

Answer 1:

我想你基本上要重新编译您插入新的HTML代码之后,因为角度刚刚插入新的代码到你的div据我了解它,不会对其进行编译。

在我看来,像正确的方法是创建一个处理您的重新编译指令。 一个可能的解决方案已经在这里讨论: http://jesusjzp.github.io/blog/2014/07/30/compile-ngbind-angularjs/

这里是从上面的链接的摘录(如果该链接不会消亡),显示它是如何应该是这样的:

HTML:

<div ng-bind-html="details" do-compile="scope"></div>

JS:

angular.module('yourAppName')
  .directive('doCompile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
      var selectedScope = attrs.doCompile && scope.$eval(attrs.doCompile);
      if (!element.hasClass('compiled')) {
        element.addClass('compiled');
        compile(element.contents())(selectedScope || scope);
      }
    };
}]);


文章来源: How to bind ng-click to a HTML block inserted inside of a directive embedded HTML block