2013-05-07 59 views
1

当用户单击一个单词时,会调用displayPopup(),这里是我创建角度应用程序的位置。我必须在$ scope中添加一些数据$ apply函数。该数据被显示出来,在弹出的,当我调用$ scope.test()或任何其他功能来更新应用程序,我得到了TypeError: Object #<Object> has no method 'test'在外部Javascript中调用角度控制器功能

我为什么不能叫我的方法!?

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

你的要求,你刚刚创建并添加到您的文档的popup范围,所以当你要求的范围你得到正是你应该得到的:$rootScope

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