ng-click在AngularJS中不起作用

时间:2013-10-31 06:06:59

标签: jquery angularjs

我遵循两条指令。第一个(recentisls)创建第二个'issuedesc'

directive('recentisls', function ($compile) {
        return {
            restrict: 'E',
            transclude: true,
            scope: {},
            controller: function ($scope, $element) {
                $scope.showIsDsc = function () {                    
                    var el = $compile("<issuedesc></issuedesc>")($scope);
                    $('body').html(el);
            },
            template: '<div ng-click="showIsDsc()"></div>',
        };
    }).

directive('issuedesc', function ($compile) {
        return {
            restrict: 'E',
            transclude: true,
            scope: {},
            controller: function ($scope, $element) {
                $scope.addcomts = function () {
                    alert("A Hello");                    
                };
            },
            template: '<input ng-click="addcomts()" type="button" value="Submit Comments"/>,
            replace: true
        };
    })

HTML代码 -

<body>
<issuedesc></issuedesc>
</body>

在浏览器中,当我们点击从issuedesc创建的按钮时,上面有效。

但是,

<body>
<recentisls></recentisls>
</body>

在浏览器中,当我们点击从recentisls创建的按钮时,上面的功能不起作用。

2 个答案:

答案 0 :(得分:0)

语法错误很少

app.directive('recentisls', function ($compile) {
    return {
        restrict: 'E',
        transclude: true,
        scope: {},
        controller: function ($scope, $element) {
            $scope.showIsDsc = function () {
                var el = $("<issuedesc></issuedesc>").appendTo('body');
                $compile(el)($scope)
            };

        },
        template: '<div ng-click="showIsDsc()">dd</div>'
    }
}).directive('issuedesc', function ($compile) {
    return {
        restrict: 'E',
        transclude: true,
        scope: {},
        controller: function ($scope, $element) {
            $scope.addcomts = function () {
                alert("A Hello");
            };
        },
        template: '<input ng-click="addcomts()" type="button" value="Submit Comments"/>',
        replace: true
    };
});

演示:Fiddle

答案 1 :(得分:0)

控制器不是使用$ compile和操作DOM的正确位置。这应该在链接功能中完成。在你的情况下,你甚至不需要真正编译。您可以将ng-if合并到模板中:

<div ng-if="!issueDescriptionVisible" ng-click="showIsDsc()"></div>
<issuedesc ng-if="issueDescriptionVisible"></issuedesc>

然后你的点击处理程序就会这样做:

$scope.showIsDsc = function() {
   $scope.issueDescriptionVisible = true;
}