将$ http和$ scope注入控制器中的函数 [英] Injecting $http and $scope into function within controller

查看:66
本文介绍了将$ http和$ scope注入控制器中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图将$ scope和$ http注入到控制器.现在,我尝试通过将代码移入控制器内的函数中来稍微重构该代码.我遇到类似的问题,似乎无法掌握Angular中依赖项注入的机制.下面是我的新代码. $ scope和$ http都未定义.我试图做的是在didSelectLanguage()触发时发出一个http请求,并将结果数据分配给父控制器$ scope中的"image"变量.有人可以启发我有关此示例中依赖注入的工作原理吗?

I asked a similar question earlier when attempting to inject $scope and $http into a controller Cannot call method 'jsonp' of undefined in Angular.js controller. Now I'm attempting to refactor that code slightly by moving the code into a function within the controller. I'm encountering similar issues and can't seem to grasp the mechanics of dependency injection in Angular. Below is my new code. Both $scope and $http are undefined. What I'm attempting to do is make an http request when didSelectLanguage() fires and assign the resulting data to the "image" variable in the $scope from the parent controller. Can someone enlighten me as to how dependency injection is supposed to work in this example?

angular.module('myApp.controllers', []).

  controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {



        $scope.didSelectLanguage=function($scope, $http) {
            console.log($scope);
            $http.jsonp('http://localhost:3000/image?quantity=1&language='+this.language+'&Flag=&callback=JSON_CALLBACK')
            .success(function(data){
            $scope.image = data;
            });

        }

  }])

推荐答案

创建控制器时:

angular.module('myApp.controllers', []).
controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {
  // ...
}]);

由于

The stuff inside the body of the controller function automatically has access to $scope and $http because of closures. Thus, there's no need to specify anything additional for a function on the $scope to have access to these things:

angular.module('myApp.controllers', []).
controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {

  $scope.didSelectLanguage = function() {
    $http.jsonp('http://localhost:3000/image?quantity=1&language=' + this.language + '&Flag=&callback=JSON_CALLBACK');
      .success(function(data) {
        $scope.$parent.image = data;
      });
  }

}]);

运行didSelectLanguage时,它会看到对$http的引用,并将该函数的 out 到达 outer 函数以获取引用的值;成功回调中的$scope也会发生同样的情况.

When didSelectLanguage is run, it sees the references to $http, and reaches out of the function into the outer function to get the value of the reference; the same happens for $scope inside the success callback.

因此,简而言之,无需将任何参数传递给您的didSelectLanguage函数,在这种情况下也没有任何理由使用$injector.

So, in short, there's no need to pass any arguments to your didSelectLanguage function, nor is there in this case any reason to use the $injector.

这篇关于将$ http和$ scope注入控制器中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆