在外部Javascript中调用Angular Controller函数

时间:2013-05-07 05:44:37

标签: javascript angularjs

当用户点击一个单词时,会调用displayPopup(),这是我创建角度应用程序的地方。我必须在$ 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");
        });
    };
});

1 个答案:

答案 0 :(得分:1)

您正在请求刚刚创建的popup范围并将其附加到您的文档中,因此当您请求其范围时,您将获得您应该获得的内容:$rootScope。< / p>

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