2

我遇到了那个烦人的 Angular 缩小问题(我真的希望这个问题在 Angular 2 中不存在)

我已经注释掉了我所有的应用程序模块注入,并逐个列出了问题所在,我认为我将其范围缩小到了我的searchPopoverDirectives

你能看出我做错了什么吗?

原始代码,产生此错误 Unknown provider: eProvider <- e

(function() { "use strict";

    var app = angular.module('searchPopoverDirectives', [])

    .directive('searchPopover', function() {
        return {
            templateUrl : "popovers/searchPopover/searchPopover.html",
            restrict    : "E",
            scope       : false,
            controller  : function($scope) {

                // Init SearchPopover scope:
                // -------------------------
                var vs = $scope;
                vs.searchPopoverDisplay = false;

            }
        }
    })

})();

然后我尝试了[]语法以尝试修复缩小问题并遇到此错误 Unknown provider: $scopeProvider <- $scope <- searchPopoverDirective

(function() { "use strict";

    var app = angular.module('searchPopoverDirectives', [])

    .directive('searchPopover', ['$scope', function($scope) {
        return {
            templateUrl : "popovers/searchPopover/searchPopover.html",
            restrict    : "E",
            scope       : false,
            controller  : function($scope) {

                // Init SearchPopover scope:
                // -------------------------
                var vs = $scope;
                vs.searchPopoverDisplay = false;

            }
        }
    }])

})();

更新: 还发现这个人造成了问题:

.directive('focusMe', function($timeout, $parse) {
    return {
        link: function(scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function(value) {
                if (value === true) { 
                    $timeout(function() {
                        element[0].focus(); 
                    });
                }
            });
            element.bind('blur', function() {
                scope.$apply(model.assign(scope, false));
            })
        }
    }
})
4

2 回答 2

8

当你缩小代码时,它会缩小所有代码,所以你的

controller  : function($scope) {

被缩小到类似的东西

controller  : function(e) {

所以,只需使用

controller  : ["$scope", function($scope) { ... }]
于 2015-05-08T15:28:35.640 回答
4

缩小 javascript 时,参数名称会更改,但字符串保持不变。您有 2 种方法可以定义需要注入的服务:

  1. 内联注释:

    phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http){
        ...
    }]);
    
  2. 使用$inject属性:

    phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);
    
    PhoneListCtrl.$inject = ['$scope', '$http'];
    
    function PhoneListCtrl($scope, $http){
        ...
    }
    

使用$inject被认为比内联注释更具可读性。最佳实践是始终有一行声明controllerservicedirective,一行用于定义注入值,最后是实现方法。由于 javascript 的提升特性,该方法可能最后定义。

记住:注解(字符串)和函数参数的顺序必须相同!

于 2015-05-08T16:24:10.110 回答