在 Angular 中使用方括号的目的是什么? [英] What is the purpose of square bracket usage in Angular?

查看:30
本文介绍了在 Angular 中使用方括号的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解MyOtherServiceMyOtherComplexService 的声明之间的区别.特别是方括号部分的目的是什么?何时使用,何时不使用?

I would like to understand the difference between the declaration of MyOtherService and MyOtherComplexService. Especially what is the purpose of square bracket part? When to use them and when not?

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

myapp.factory('MyService', function($rootScope, $timeout) {
    return {
        foo: function() {
            return "MyService";
        }
    }
});

myapp.factory('MyOtherService', function($rootScope, $timeout, MyService) {
    return {
        foo: function() {
            return "MyOtherService";
        }
    }
});

myapp.factory('MyOtherComplexService', ['$rootScope', '$timeout', 'MyService', function($rootScope, $timeout, MyService) {
    return {
        foo: function() {
            return "MyOtherComplexService";
        }
    } 
}]);

myapp.controller('MyController', function($scope, MyOtherService, MyOtherComplexService) {

    $scope.x = MyOtherService.foo();
    $scope.y = MyOtherComplexService.foo(); 
});

推荐答案

它可以缩小 AngularJS 代码.AngularJS 使用参数名称将值注入您的控制器函数.在 JavaScript 缩小过程中,这些参数被重命名为较短的字符串.通过使用字符串数组告诉函数注入了哪些参数,AngularJS 仍然可以在重命名参数时注入正确的值.

It enables AngularJS code to be minified. AngularJS uses parameter names to inject the values to your controller function. In JavaScript minification process, these parameters are renamed to shorter strings. By telling which parameters are injected to the function with a string array, AngularJS can still inject the right values when the parameters are renamed.

这篇关于在 Angular 中使用方括号的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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