angular js 工厂内的访问范围

Access scope inside an angular js factory

我正在使用 ionic 框架并且需要能够从我的代码中的多个位置调用弹出窗口,所以我想我会把它移到一个工厂中。弹出窗口使用输入字段,我想获取它的值。通常我只会调用 $scope.parentGate.answer 但因为它在工厂中所以我无权访问范围。我有什么想法可以获取输入字段的值吗?

这是我的代码:

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();
                      }
                    }
                  }
                ]
            });
        }
    };
});

事实上,您可以访问您工厂中的范围。你不能的原因是你的 parentGate.show 函数中没有这样一个叫做 $scope 的变量。

您似乎想使用工厂来弹出对话框。

我认为在你的情况下,当你尝试调用

时,你会将范围作为参数传递给你
angular.module("yourApp").controller("testController", function($scope, parentGate){
    parentGate.show($scope, callback);
});

并且在您的工厂中,当您尝试更改 $scope 下的 属性 值时,(onTap 回调)您应该使用 scope 而不是 $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 is the demo code.
Here is the reason why we want to change $scope to scope in your onTap callback(演示结束)

希望这会奏效。 :)