Reputation: 500
I need to add dynamically a button to my html code. The thing is that it has an angular link inside and it dosen't work once the page loads. I've been researching and it looks like I need to use $compile in order to make it work.
Here the two codes I tried:
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);
}]);
This code gives me no error and even puts the button where it has to be, but the link still dosen't works.
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);
This second line of code gives me an error: "ReferenceError: $compile is not defined"
I have both codes (not at the same time) in the controller.
Any ideas?
Upvotes: 2
Views: 3511
Reputation: 201
I meet the same problem before, I fixed it by
app.controller('controller', [
'$scope','$http', '$window', 'promiseTracker', '$timeout', '$compile',
function($scope, $http, $window, promiseTracker, $timeout, $compile) {
...........
}]);
Define the $compile before you use it, so there won't be such error of "ReferenceError: $compile is not defined".
Upvotes: 4
Reputation: 160
Why not just make it a directive? Angular directives call $compile by default and you can give it an option to instantiate its own scope.
angular
.module('app.module')
.directive('myButtonDirective', myButtonDirective);
function myButtonDirective() {
var directive = {
templateUrl: 'app/button-directive.html',
scope: {},
restrict: 'E',
replace: true
};
return directive;
}
Then your app/button-directive.html
would look like
<a ui-sref="app.form.matter({method:'new',id:'\'})" type="button" class="btn dark_blue_bomhard m-b-5 nuevocliente">New matter</a>
All you have to do is place your new directive in your html
<div class="toolbar">
/** Your HTML Here **/
<my-button-directive></my-button-directive>
</div>
Upvotes: 2