0

$I have a custom javascript object, that can fire events. I would like to access the angular $scope inside the event-handler, but I have read somewhere that using angular.element(...).scope() is not good, because it's only meant for testing.

My other idea was to register the handle on my object inside the controller, but this is not working (looks like $scope.somevalue gets set, but I don't think $scope is the same object).

I have found many answers here on Stack Overflow for similar questions, but they all seem to be using directives. All I want is to get a value from the object when it's updated, and display it.

Here are the two ways I have tried.

var myObj = GetMyObjInstance();

// Working, but apparently it's not good practise to call .scope() on an element.
myObj.onUpdated = function(){
    console.log("myObj updated");
    var v = myObj.getValue();
    var controllerDiv = document.getElementById("controller");
    var $scope = angular.element(controllerDiv).scope();

    $scope.apply(function(){
       $scope.someValue = v; 
    });
}

// Tried to do this, thinking i would get closure on the scope.
angular.module('myApp', []).controller('controller', function($scope){
   myObj.onUpdated = function(){
       console.log("myObj updated"); // Gets logged to console...
       var v = myObj.getValue();
       $scope.somevalue = v; // ... but somevalue does not get displayed. 
       $scope.apply(); // Error, says it's not a function, so maybe this is not the right object?.
   } 
});
3
  • Try $scope.$apply() instead of $scope.apply(). But nevertheless, you should try to use directives and/or components. Commented Apr 8, 2016 at 12:22
  • Have you tried $scope.$watch()? Commented Apr 8, 2016 at 12:26
  • please console.log(v) and check it. If it is ok just change $scope.apply(); to $scope.$apply(); Commented Apr 8, 2016 at 12:33

2 Answers 2

1

Use AngularJS directives to handle events and update scope.

app.directive("xdEvent", function() {
    return linkFn(scope, elem, attrs) {
        elem.on("event", function(e) {
            scope.$eval(attrs.xdEvent, {$event: e});
            scope.$apply();
        });
    };
};

USAGE

<div xd-event="fn($event)"></div>
Sign up to request clarification or add additional context in comments.

Comments

0

I think using a Service instead of a controller is a better practice. You can call a service from outside javascript with the injector like explained in this thread : Call angularjs service from simple js code

If it is still important for you to access this variables from controller, you can use $watch to tell your controller to update itself when the service variables change.

Hope this help.

A+

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.