【问题标题】:Minification with Directives and anonymous AngularJS controllers使用指令和匿名 AngularJS 控制器进行缩小
【发布时间】:2015-07-24 16:00:33
【问题描述】:

我在我的应用程序中使用“ng-strict-di”指令来防止缩小失败。但现在我的指令出错了。

错误:[$injector:strictdi] function($scope, element, attrs) 没有使用显式注解,无法在严格模式下调用

如何将 $scope 显式添加为匿名控制器函数的依赖项?这是我的指令。

var myApp = angular.module("myApp",[]);
myApp.directive('myDirective', function(){
  return{
    restrict: 'A',
    template: '<h4> {{myController.msg}} </h4>',
    controller: function($scope, element, attrs){
      $scope.myController = this;
      this.msg = "Hello world";
    };
});

我试过了:

var myApp = angular.module('myApp ', ['$scope'])

但我收到此错误: 错误:[$injector:modulerr] 无法实例化模块

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您需要指令控制器的缩小安全语法:

    controller: ["$scope", "element", "attrs", function($scope, element, attrs){
      $scope.myController = this;
      this.msg = "Hello world";
    }];
    

    基于这些参数,我猜你想要一个 link 函数(只是猜测):

    link: function($scope, element, attrs){
      $scope.myController = this;
      this.msg = "Hello world";
    };
    

    【讨论】:

    • 第一部分还可以。 link 的选择应该比它的参数更有效。此外,thislink 中未定义(不管$scope.myController = this; 是controllerAs 的用例,根本不应该存在)。
    • 谢谢!我认为所有需要的是控制器: ["$scope", function ($scope, element, attrs)
    • @estus -- 是的,这是基于传入控制器函数的参数的假设
    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多