angularjs - Angular 直接将 $scope 参数从 View 发送到服务或工厂

标签 angularjs angularjs-scope angularjs-factory

我有一个工厂,需要从 View 中调用工厂。 我想用两个参数调用工厂。 是否可以从模板发送$scope?

因为,我在多个地方使用同一工厂。

<input name="accnum" ng-blur="myservice.getAccountDetailsToDisplay($scope, accno)" />

Controller ,

 $scope.myservice= getAllDetailsService;

服务中,

tellerApp.factory('getAllDetailsService',['$rootScope', '$resource', '$http', '$filter', '$window',  function ($rootScope, $resource, $http, $filter, $window) {
    return{ 
           getAccountDetailsToDisplay: function ($scope, accountnumber) {
           console.log('>>>>>>');   
          }
};      
}]);

最佳答案

Service should be directly depends on scope, they could be indirectly depend on each other. If you pass $scope to the service it will become tightly couple to that specific controller.

就像您的情况一样,您只传递帐号,然后服务将执行所需的操作,例如执行ajax调用或从某处获取数据。

工厂

tellerApp.factory('getAllDetailsService', ['$rootScope', '$resource', '$filter', '$window', function($rootScope, $resource, $http, $filter, $window) {
    return {
        getAccountDetailsToDisplay: function(accountnumber) {
            return $http.get('/getAccountDetails?accountnumber=' + accountnumber).then(function(res) {
                //here you could do your addtional operation on data.
                return res.data; //giving access to data
            });
        }
    };
}]);

Controller

$scope.myservice= getAllDetailsService
//this line will ensure updation in scope
$scope.myservice.accountDetailsToDisplay = getAllDetailsService.accountDetailsToDisplay; 

标记

 <input name="accnum" ng-blur="myservice.getAccountDetailsToDisplay(accno)"/>

同样,在上面的代码中,我没有使用 $scope 作为参数,服务方法只会返回从服务中获取的任何数据,并且无论谁使用该服务方法都只能获得通过以下方式返回的数据服务。从服务 Controller 获取数据后,在其自己的上下文中修改范围。

关于angularjs - Angular 直接将 $scope 参数从 View 发送到服务或工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30636114/

相关文章:

javascript - 似乎无法将 Angular-JWT 注入(inject)工厂

AngularJS:检查用户角色以确定用户是否有权查看页面

javascript - 无法使用 AngularJS 显式 `$http` 语法注入(inject) `app.controller`?

javascript - 将多个 Controller 中的 AngularJS 范围对象合并为一个对象

angularjs - 如何在angularjs中重绘图表?

javascript - 当工厂可以做同样的事情时,为什么要使用 $rootScope 在 Controller 之间共享数据?

html - 本地托管网站未正确路由

javascript - 为什么使用 ui-router 时会出现重复的 div?

angularjs - Angular-ui-router:解析根状态

angularjs - 发送 $http.get 两次