Вопрос

I append DOM element to body. Wrote the code in factory.

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);
    });

everything works except the ng-click. I got this error when I click the div:

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

What did I do wrong? Thanks

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top