fjaxyu fjaxyu - 2 months ago 9
Javascript Question

JS - create and pass a function, that is to be evaluated within the context of another scope

I'm working with angular and bootstrap tour and I want to try and keep the objects in an area of their own, so they don't have to be stored in the controller. I want to store an object in the service, but it also has functions in the object. When those get "eval()" 'd, they are firing in the scope of the service, instead of the controller where they are passed. Specifically, "$scope" has no context in the service, but does in the controller.

Heres a sample of the code:

var returnedObj = {
steps: [
{
element: '#newProduct',
title: 'Create Products',
placement: 'bottom',
content: 'Create new products here'
}
],
backdrop: true,
//The function that I want to interact with the $scope through the controller
onShow: function (tour) {
$scope.tourDisabled = true;
$scope.filter.availability = 'all';
$scope.filter.gallery = 'Show All';
$scope.updateFilter();
}
};


I've tried JSON.stringify and JSON.parse, but it doesn't work with functions. Is this just hopeless to be done?

Aside from $rootScope, is this possible?

Answer

You should pass in $scope, or whatever context you need, as an argument to your function:

onShow: function (tour, $scope) {
        $scope.tourDisabled = true;
        $scope.filter.availability = 'all';
        $scope.filter.gallery = 'Show All';
        $scope.updateFilter();
Comments