1

I have a function called load in a .js file. :

$scope.load = function(id){

    alert(id);
};

This file is imported via a .jsp file and I'm attempting to call this function from this page :

angular.element(document).ready(function ($scope) {

        $scope.load('76348')


    });

The controller is defined within a div element :

<div ng-controller="mycontroller">

</div>

But I receive this error :

Uncaught TypeError: Object function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method 'showLinks' 

I think a new $scope is being created since the method is not being found ? Is there a mechanism for accessing the $scope from the .jsp page ? I just want to fire the angularjs method on page load so any other suggestions are appreciated.

blue-sky
  • 51,962
  • 152
  • 427
  • 752

1 Answers1

0

Assuming you've got an ng-controller on your body, you'd use

angular.element('body').scope().load(76348);

But I should stress that this is a really bad idea. This is not jQuery. You really shouldn't access scopes like this ever because it breaks encapsulation, adds confusion to your app, and goes against best practices.

Jonathan Rowny
  • 7,588
  • 1
  • 18
  • 26
  • the controller is defined as part of a div, ive updated the question. Does this mean I need to assign an id to this div and use something like angular.element('MyControllerDivId').scope().load(76348); – blue-sky Feb 04 '14 at 17:03
  • So I named my div "mydiv" and to get the scope I used : var scope = angular.element(document.getElementById("mydiv")).scope(); But perhaps this is a bad practice ? The answer by fallwind in this question : http://stackoverflow.com/questions/15424910/angularjs-access-scope-from-outside-js-function led me to this. – blue-sky Feb 04 '14 at 17:19
  • Yes, or just `angular.element('#mydiv')` but this is all bad practice. You should never do any of this. – Jonathan Rowny Feb 04 '14 at 18:01