0

我将 DOM 元素附加到正文。在工厂编写代码。

var templateElement = angular.element('<div class="popup modal-body"><div class="button-cancel" type="button" ng-click="closePopup()"></div>'+content+'</div>');
    var scope = {};
    scope.closePopup = function(){
      var popup = angular.element(document.querySelector('.popup'));
      popup.remove();
    }

    var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
      body.append(clonedElement);
    });

一切正常,除了 ng-click。单击 div 时出现此错误:

Uncaught TypeError: Object #<Object> has no method '$apply'

我做错了什么?谢谢

4

1 回答 1

4

According to the docs, the function returned by $compile() takes a Scope object as its first argument. You supply a normal JS object (which does not have an $apply method of course).

If you want to create a new scope, you can inject the $rootScope (through Dependency Injection) and use its $new() method:

app.factory('myFactory', function($rootScope) {
    var scope = $rootScope.$new();
    ...
});

It seems a little bizarre to create an new scope inside a factory though, so providing more details on what you are ultimately trying to achieve might help someone suggest a better approach.

于 2014-01-07T11:54:31.877 回答