如何在Angular.js对象相关的函数参数名连接到其他对象? [英] How do the function argument names in Angular.js objects connect to other objects?

查看:133
本文介绍了如何在Angular.js对象相关的函数参数名连接到其他对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我已经取得了服务,并在Angular.js控制器模块,我能够访问控制器内部的服务,像这样:

Let's say I have made a module with a service and a controller in Angular.js, I am able to access that service inside of the controller like so:

var myapp = angular.module('my-app', []);

myapp.factory('Service', function() {
  var Service = {};
  Service.example = 'hello';
  //etc..
  return Service;
});

myapp.controller('mainController', function($scope, Service) {
  $scope.greeting= Service.example;
});

在这个例子中,服务对象将被传递到控制器,并构造了code,像这样将不会改变code的行为:

In this example, the Service object will be passed to the controller, and structuring the code like so will not change the behavior of the code:

myapp.controller('mainController', function(Service, $scope) {
  $scope.greeting= Service.example;
});

那么,如何Angular.js知道什么函数的参数是什么意思?

so, how does Angular.js "know" what the function arguments mean?

推荐答案

角简单解析的toString()再依赖项的名称的功能的presentation 。从的文档

Angular simply parses the toString() representation of the function for the names of dependencies. From the docs:

在JavaScript调用的toString()在函数返回函数定义。那么,定义可以分析和函数的参数可以被提取。

In JavaScript calling toString() on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted.

但是,请注意,如果你的code为缩小的这种做法将失败。出于这个原因,角支持替代语法(我会用它建议总是),使用数组:

However, note that this approach will fail if your code is minified. For that reason, Angular supports an alternative (I would suggest always using it) syntax, using an array:

myapp.controller('mainController', ["$scope", "Service", function($scope, Service) {
  $scope.greeting= Service.example;
}]);

这篇关于如何在Angular.js对象相关的函数参数名连接到其他对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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