我需要在我的 html 代码中动态添加一个按钮。问题是它内部有一个 Angular 链接,一旦页面加载它就不起作用。我一直在研究,看起来我需要使用 $compile 才能让它工作。
这是我试过的两个代码:
代码 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);
}]);
这段代码没有给我任何错误,甚至把按钮放在了它必须在的地方,但链接仍然不起作用。
代码 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: $compile is not defined”
我在 Controller 中有两个代码(不同时)。
有什么想法吗?
最佳答案
我遇到过同样的问题,我通过以下方法解决了
app.controller('controller', [
'$scope','$http', '$window', 'promiseTracker', '$timeout', '$compile',
function($scope, $http, $window, promiseTracker, $timeout, $compile) {
...........
}]);
在使用之前先定义$compile,这样就不会出现“ReferenceError: $compile is not defined”这样的错误。
关于angularjs - Angular $compile 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35654881/