在AngularJs中从视图到工厂访问$scope数据
Accessing $scope data from view to factory in AngularJs
如何在angularjs中从view到factory访问$scope数据?我可以访问$scope。项,但是当我需要在工厂中使用它来使用数据并生成pdf时,我无法访问它。
angular.module('myApp', [])
.controller('myCtrl', function($scope, $http, testFactory) {
$scope.link = "http://localhost:3450/loading.html";
testFactory.all().then(
function(res){
$scope.link = res;
},
function(err){
console.log(err);
}
);
})
.factory('testFactory', function($q){
var pdfInfo = {
content: [
//data should be here...
]
};
var link = {};
function _all(){
var d = $q.defer();
pdfMake.createPdf(pdfInfo).getDataUrl(function(outputDoc){
d.resolve(outputDoc);
});
return d.promise;
}
link.all = _all;
return link;
});
我使用factory,当我从视图中单击generate按钮时,它将等待直到pdf生成。因为我以前没有这样做过,我需要点击两次按钮才能生成pdf。
您可以将数据作为参数传递给工厂函数参数。
angular.module('myApp', [])
.controller('myCtrl', function($scope, $http, testFactory) {
var pdfInfo = {
content: $scope.items
};
$scope.link = "http://localhost:3450/loading.html";
testFactory.all(pdfInfo).then(
function(res) {
$scope.link = res;
},
function(err) {
console.log(err);
}
);
})
.factory('testFactory', function($q) {
var link = {};
function _all(pdfInfo) {
var d = $q.defer();
pdfMake.createPdf(pdfInfo).getDataUrl(function(outputDoc) {
d.resolve(outputDoc);
});
return d.promise;
}
link.all = _all;
return link;
});
我做到了。我忘记把$scope.items
寄到我的工厂了。我所做的就是在控制器中添加testFactory.all($scope.items)
而不是普通的testFactory.all()
。
然后在我的工厂,
我使用了function _all(value)
,所以我可以使用视图通过控制器传递的值。我不确定这是否是正确的方法,但它有效。请建议好的做法,如果你有。
将$scope移到其他服务是一种不好的做法,因为它们可能会改变它并影响您的控制器逻辑。它将在控制器和其他服务之间建立耦合。如果您的工厂需要来自控制器的数据,那么最好将这些参数传递给工厂的函数。
编辑:我看到你设法做到了,是的-传递$scope。Items是首选的方法(例如,不传递$scope)。
相关文章:
- Ng出口无法访问父$scope
- 如何从其他方法访问Angular.js$scope
- 我如何访问在 Angular JS 的 .then() 中定义的$scope数组
- 从同一控制器 Angularjs 中的另一种方法访问$scope变量
- UI-GRID:访问$scope的问题
- ng-repeat中的ng-options - 无法访问$scope中的选定项目
- AngularJS在方法之外访问$scope
- 在$routeChangeSuccess指令的模板中访问$scope
- 在AngularJS中的$http成功回调之外无法访问$scope变量值
- 在AngularJs中从视图到工厂访问$scope数据
- 在不访问$scope的情况下自动更改输入字段
- AngularJS:在$routeProvider完成请求后访问' $scope '值
- 在用函数作为模板的重复AngularJS指令中访问' $scope '
- 从AngularJS服务内部访问$scope属性
- 如何访问“$scope.search.value”
- 我如何获得登录函数能够访问$scope.names
- 无法在angular中访问$scope
- 如何在用我的HTML编写的javascript中访问scope.postresult值
- 从ng视图访问$scope时遇到问题
- AngularJS -如何从指定作用域的指令中访问$scope