简体   繁体   English

如何将服务注入Angularjs中的方法

[英]How to inject services into methods in Angularjs

I'm trying to understand dependency injection in AngularJS. 我试图理解AngularJS中的依赖注入。

Right now, I'm trying to inject $interpolate and $eval into my controller, but reading the documentation didn't clarify because I don't have a good foundation on Angular. 现在,我正在尝试将$interpolate and $eval注入到我的控制器中,但是阅读文档并不清楚,因为我对Angular缺乏很好的基础。

Take the following code that demonstrates the issue I don't understand: 使用以下代码演示我不了解的问题:

var module = angular.module('ngAppDemo',[ ]);

module.controller('ngAppDemoController', function($scope, $parse) {
  $scope.a = 1;
  $scope.b = 2;
  $scope.myHTML = '{{a}}';

});

Can someone help me understand how to inject and $interpolate the myHTML string? 有人可以帮助我了解如何注入和$interpolate myHTML字符串吗? Or if interpolation is not correct in evaluating that string, what is? 或者,如果在评估该字符串时插值不正确,那是什么? It's a weird case, but I'm just trying to learn right now. 这是一个奇怪的情况,但是我现在正试图学习。

you're very close. 你很亲近 just need to declare it as module dependency and add to function parameters. 只需将其声明为模块依赖项并添加到函数参数即可。 (i think this should work) (我认为这应该工作)

var module = angular.module('ngAppDemo',['$interpolate' ]);

module.controller('ngAppDemoController', function($scope, $parse, $interpolate) {
  $scope.a = 1;
  $scope.b = 2;
  $scope.myHTML = '{{a}}';

});

i've been declaring controllers and injection in this way: 我一直以这种方式声明控制器和注入:

angular.module('app').controller(
        'generator', 
        ['myService', '$http', '$scope', '$interpolate', generator]
);

function generator(myService, $http, $scope, $interpolate) {
    $scope.foo = 'bar';
}

where the controller object (in my case generator ) is passed in to the module declaration 控制器对象(在我的情况下为generator )传递到模块声明的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM