Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – 角度js工厂内的访问范围大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用离子框架,并且需要能够从我的代码中的多个位置调用弹出窗口,所以我想我会将它移动到工厂中.弹出窗口使用输入字段,我想获得它的值.通常我只会调用$scope.parentGate.answer,但因为它在工厂中我无法访问范围.我有什么想法可以获得输入字段的值

这是我的代码

angular.module('starter.services',[])
.factory('parentGate',function ($ionicPopup,Helpers) {
    return {
        Show: function(scope,@R_616_6048@sCallBACk) {
            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");
                        @R_616_6048@sCallBACk();
                      } else {
                        console.log("wrong!");
                        e.preventDefault();
                      }
                    }
                  }
                ]
            });
        }
    };
});

解决方法

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

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

我认为在你的情况下,当你尝试调用时,你会将范围作为参数传递给你

angular.module("yourApp").controller("TESTController",function($scope,parentGatE){
    parentGate.show($scope,callBACk);
});

在您的工厂中,当您尝试更改$scope((onTap回调)下的属性值时,您应该使用范围,而不是$scope

onTap: function(E) {
    //if ($scope.parentGate.answer == first + second) { 
    if (scope.parentGate.answer == first + second) { 
        console.log("correct");
        @R_616_6048@sCallBACk();
     } 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(演示闭幕)

希望这会奏效.

本图文内容来源于网友网络收集整理提供,作为学习参使用,版权属于原作者。

大佬总结

以上是大佬教程为你收集整理的angularjs – 角度js工厂内的访问范围全部内容,希望文章能够帮你解决angularjs – 角度js工厂内的访问范围所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。