angularjs - Access scope inside an angular js factory -
i'm using ionic framework , need able call popup muliple places in code thought move factory. popup uses input field , want value of it. call $scope.parentgate.answer
because it's in factory don't have access scope. ideas how can value of input field?
here's 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 ' + first + ' + ' + second + ' equal?' // 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) { // // can't access $scope.parentgate.answer here. // how else can it? // if ($scope.parentgate.answer == first + second) { console.log("correct"); successcallback(); } else { console.log("wrong!"); e.preventdefault(); } } } ] }); } }; });
in fact, can access scope in factory. reason cannot there's no such variable called $scope
in parentgate.show function.
seems want use factory pop dialog.
i think in case, pass scope parameter when u try invoke
angular.module("yourapp").controller("testcontroller", function($scope, parentgate){ parentgate.show($scope, callback); });
and in factory, when try change property value under $scope, (ontap callback) 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 demo code.
here reason why want change $scope scope in ontap callback (demo closure)
hope work. : )
Comments
Post a Comment