Access scope inside angular js factory
I'm using an ionic framework and should be able to call the popup from multiple places in my code, so I thought I moved it to a factory. The popup is using an input field and I want to get its value. Usually I would just call $scope.parentGate.answer
, but since it's in a factory, I don't have access to the scope. Any ideas how I can get the value of the input field?
Here's my code:
angular.module('starter.services', [])
.factory('parentGate', function ($ionicPopup, Helpers) {
return {
Show: function(scope, SuccessCallback) {
var first = Helpers.RandomNumber(1, 5) * 10;
var second = Helpers.RandomNumber(11, 22);
var title = 'What does ' + first + ' + ' + second + ' equal?'
// An elaborate, custom popup
return $ionicPopup.show({
template: '<h4 class="text-center">' + title + '</h4><div class="list"><label class="item item-input"><input type="number" ng-model="parentGate.answer" placeholder="Answer..."></label></div>',
title: "Parent Gate",
//subTitle: title,
scope: scope,
buttons: [
{ text: 'Cancel' },
{
text: 'Continue',
type: 'button-positive',
onTap: function(e) {
//
// I can't access $scope.parentGate.answer here.
// How else can I do it?
//
if ($scope.parentGate.answer == first + second) {
console.log("correct");
SuccessCallback();
} else {
console.log("wrong!");
e.preventDefault();
}
}
}
]
});
}
};
});
source to share
You can actually access the scope in the factory. The reason you can't is there is no such variable called $scope
in your parentGate.show function.
You seem to want to use a factory to open the dialog.
I think in your case you will pass the scope to you as a parameter when you try to call
angular.module("yourApp").controller("testController", function($scope, parentGate){
parentGate.show($scope, callback);
});
And in your factory, when trying to change the value of a property in $ scope (onTap callback), you should use scope
, not $scope
onTap: function(e) {
//if ($scope.parentGate.answer == first + second) {
if (scope.parentGate.answer == first + second) {
console.log("correct");
SuccessCallback();
} else {
console.log("wrong!");
e.preventDefault();
}
}
Here's a demo code.
This is why we want to change $ scope to scope in your onTap callback (Demo Closure)
Hope it works. :)
source to share