添加ng-click到使用angular.element创建的div

时间:2016-06-30 23:51:59

标签: angularjs

我有以下指令,其中有两个孩子div。第二个div(使用angular.element创建)应该是可以解决的。由于我是使用angular.element创建的,因此我尝试使用ng-click函数添加attr,但这并不起作用。这段代码有什么问题?

       app.directive('mydir', function () {

                var directive = {};

                directive.restrict = 'EA';

                directive.replace = true;

                directive.scope = {
                     control: '=',
                };

                directive.template = '<div id="root"></div>';

                directive.link = function (scope, element, attrs) {

                        var wrap = angular.element('<div id="wrap"></div>');
                        element.append(wrap);                               
                        var node = angular.element('<div id="node"></div>');
                        node.attr('ng-click', 'toggle()');   // <--- this doesn't work
                        wrap.append(node);

                        scope.toggle = function () {
                            alert('clicked');
                        };
                });

                return directive;

            });

1 个答案:

答案 0 :(得分:3)

元素必须使用角度$compile服务编译:

       app.directive('mydir', function ($compile) { // added dependency here

                var directive = {};

                directive.restrict = 'EA';

                directive.replace = true;

                directive.scope = {
                     control: '=',
                };

                directive.template = '<div id="root"></div>';

                directive.link = function (scope, element, attrs) {

                        var wrap = angular.element('<div id="wrap"></div>');
                        element.append(wrap);                               
                        var node = angular.element('<div id="node"></div>');
                        node.attr('ng-click', 'toggle()');   // <--- this doesn't work
                        var content = $compile(node)(scope);
                        wrap.append(content);

                        scope.toggle = function () {
                            alert('clicked');
                        };
                });

                return directive;

            });

Here是关于使用$compile的简短教程。希望有所帮助