1

当用户单击一个单词时,会调用 displayPopup(),这就是我创建 Angular 应用程序的地方。我必须在 $scope.$apply 函数中拍摄一些数据。该数据显示在弹出窗口中,但是当我调用 $scope.test() 或任何其他函数来更新应用程序时,我得到一个TypeError: Object #<Object> has no method 'test'

为什么我不能调用我的方法!?

 displayPopup = function(event) {

    var popup = document.createElement('div');
    popup.innerHTML = popupContent;

    popup.id = "wordly-popup";
    popup.style.top = event.clientY + "px";
    popup.style.left = event.clientX + "px";
    $("body").append(popup);

    var $injector = angular.bootstrap(popup, ['myApp']);
    var $scope = angular.element(popup).scope();

    $scope.$apply(function(){
        $scope.word = getSelectionText();
        $scope.contextSentence = currentSentence.innerHTML;
               $scope.test(); // NOT WORKING


    });

}

这是我的应用程序定义:

var myApp = angular.module("myApp", []);

myApp.controller("PopupCtrl", function($scope, $http) {

    $scope.showLoading = false;
    var currentPOS = null;

    $scope.setPOS = function(pos) {
        currentPOS = pos;
    }

    $scope.getDetails = function() {

        if ($scope.word.length == 0) {
            $scope.definitions = null;
            $scope.partsOfSpeech = {};
        }

        $scope.showLoading = true;

        currentPOS = null;
        $http.get('http://localhost:3000/words/definitions/' + $scope.word).then(function(response) {
            $scope.showLoading = false;
            console.log(response.data[1]);
            $scope.syllables = response.data[1];
            $scope.definitions = response.data[0];
            $scope.partsOfSpeech = _.uniq(_.pluck(response.data[0], "partOfSpeech"));
        });
    };

    $scope.posFilter = function(definition) {
        if (currentPOS == null) return true;
        return definition.partOfSpeech == currentPOS;
    };

    $scope.test = function()
    {
        console.log("hello!");
    }
});

myApp.directive("hovercolor", function() {
    return function(scope, element, attrs) {
        element.bind("mouseenter", function(data) {
            element.css("background-color", "#f89406");
            element.css("color", "white");
            element.css("cursor", "pointer")
        });

        element.bind("mouseleave", function(data) {
            element.css("background-color", "transparent");
            element.css("color", "black");
        });
    };
});
4

1 回答 1

1

您正在请求popup您刚刚创建并附加到文档中的$rootScope.

我假设它popupContent包含表示 的 HTML ng-controller="PopupCtrl",这可能是您想要的范围。您可以将ng-controller属性设置为 on popup,也可以从中获取所需的范围popup.firstChild

于 2013-05-07T06:06:16.863 回答