angularjs – 角度js工厂内的访问范围
发布时间:2020-12-17 17:04:16 所属栏目:安全 来源:网络整理
导读:我正在使用离子框架,并且需要能够从我的代码中的多个位置调用弹出窗口,所以我想我会将它移动到工厂中.弹出窗口使用输入字段,我想获得它的值.通常我只会调用$scope.parentGate.answer,但因为它在工厂中我无法访问范围.我有什么想法可以获得输入字段的值? 这
|
我正在使用离子框架,并且需要能够从我的代码中的多个位置调用弹出窗口,所以我想我会将它移动到工厂中.弹出窗口使用输入字段,我想获得它的值.通常我只会调用$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 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. 希望这会奏效. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
