2016-02-26 78 views
2

我需要动态地将一个按钮添加到我的html代码中。问题在于它内部有一个角度链接,一旦页面加载就无法工作。我一直在研究,它看起来像我需要使用$编译,以使其工作。

下面两个代码我想:

CODE 1

angular.injector(['ng']).invoke(['$compile', '$rootScope', function(compile, rootScope){ 

     var scope = rootScope.$new(); 

     var result = compile('<a ui-sref="app.form.matter({method:\'new\',id:\'\'})" type="button" class="btn dark_blue_bomhard m-b-5 nuevocliente" >New matter</a>')(scope); 
     scope.$digest(); 
     $("div.toolbar").append(result); 
    }]); 

此代码给了我没有错误,甚至把它必须是该按钮,但链接仍然这么想的作品。

CODE 2

angular.element("div.toolbar").append($compile('<a ui-sref="app.form.matter({method:\'new\',id:\'\'})" type="button" class="btn dark_blue_bomhard m-b-5 nuevocliente" >New matter</a>'))(scope); 

此代码第二行给我一个错误:“的ReferenceError:$编译没有定义”

我有两个代码(不是在同一时间)在控制器中。

任何想法?

+0

混淆自己打针改变字符串版本和功能参数的名称 – charlietfl

+0

按钮不起作用,因为你不包括'在喷油器的UI,route'。 – georgeawg

回答

4

我之前达到同样的问题,我固定它通过

app.controller('controller', [ 
    '$scope','$http', '$window', 'promiseTracker', '$timeout', '$compile', 
    function($scope, $http, $window, promiseTracker, $timeout, $compile) { 
    ........... 
    }]); 

在使用它之前定义$ compile,所以不会出现“ReferenceError:$ compile is not defined”这样的错误。

2

为什么不让它指令? Angular指令默认调用$ compile,你可以给它一个选项来实例化自己的作用域。

angular 
    .module('app.module') 
    .directive('myButtonDirective', myButtonDirective); 

function myButtonDirective() { 
    var directive = { 
     templateUrl: 'app/button-directive.html', 
     scope: {}, 
     restrict: 'E', 
     replace: true 
    }; 
    return directive; 
} 

然后你app/button-directive.html看起来像

<a ui-sref="app.form.matter({method:'new',id:'\'})" type="button" class="btn dark_blue_bomhard m-b-5 nuevocliente">New matter</a> 

所有你需要做的就是把你的新指令在HTML

<div class="toolbar"> 
    /** Your HTML Here **/ 
    <my-button-directive></my-button-directive> 
</div> 
+0

这看起来像我想知道如果我想使用角度。谢谢。 我试过这段代码。我没有得到任何错误,但按钮不出现。如果我查看代码,按钮就在那里。要继续尝试。 –