我有以下功能:

$scope.addProduct = function($event, obj) {

    var myEl = angular.element($event.target);

    myEl.parent().html('<button class="btn btn-danger btn-xs" ng-click="removeProduct('+ obj.id +')">Remove from Widget</button>');

};

$scope.removeProduct = function(id) {
    console.log('Remove ->' + id);

};


当我单击“ addProduct”时,它起作用,但是当我单击“ removeProduct”时,则不起作用。看起来它没有听我添加的新按钮的单击。我该如何解决?

最佳答案

为了使ngClick生效,您需要首先编译HTML并将其链接到$scope

.controller('someCtrl', function ($compile, $scope) {
    ...

    $scope.addProduct = function($event, obj) {
        var myEl = angular.element($event.target);
        var myBtn = $compile('<button class="btn btn-danger btn-xs" ng-click="removeProduct('+ obj.id +')">Remove from Widget</button>')($scope);
        myEl.after(myBtn);
    };

    $scope.removeProduct = function(id) {
        console.log('Remove ->' + id);
    };
});




更新:

Kos Prov's comment是非常正确的-有时您会考虑解决问题,但首先您并不认为问题是错误的。

因此,当然,操作DOM应该是指令的责任,因此我创建了一条指令来执行您想要的操作(根据您的问题):

app.directive('removableProduct',函数($ compile){
        var btnTmpl =
            ''+
                “从小部件中删除” +
            '';

    return {
        restrict: 'A',
        scope: {item: '='},
        template: '<div ng-click="addProduct($event)">{{item.description}}</div>',
        controller: function ($scope) {
            $scope.addProduct = function (evt) {
                var myEl = angular.element(evt.target);
                var myBtn = $compile(btnTmpl)($scope);
                myEl.after(myBtn);
            };
            $scope.removeProduct = function(id) {
                console.log('Remove -> ' + id);
            };
        }
    };
});




另请参见此short demo

关于javascript - Angular ng-click事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24054730/

10-12 15:49