javascript - AngularJS 中的 $injector.unpr 错误

标签 javascript angularjs

我是 AngularJS JavaScript 新手。刚开始学它。我正在尝试一些小示例程序。这是我尝试过的,但它抛出错误。

<body ng-app="myApp">

  <div ng-controller="myCtrl"> 
    {{time}}
    <br>
  </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
  var app = angular.module("myApp", []);

  app.service('hexafy', ['',
    function() {
      this.myfunc = function(num) {
        return num.toString(16);
      }
    }
  ]);

  app.controller('myCtrl', ['hexafy', '$scope', '$interval',
    function(hexafy, $scope, $interval) {
      $scope.time = new Date().toLocaleTimeString();
      $interval(function() {
        $scope.time = new Date().toLocaleTimeString();
      }, 1000);
      // $scope.hex = hexafy.myfunc(255);
    }
  ]);
</script>

最佳答案

当代码被缩小并保留参数的映射时,使用数组语法。有关更多信息,请参阅我的另一个答案 Why we Inject our dependencies two times in angularjs? .

代码中,由于没有向hexafy服务传递任何参数,因此不需要使用数组语法并传递空字符串。

app.service('hexafy', ['',
    function() {

使用正常语法。

app.service('hexafy', function() { // <-- Remove `[` and empty string from here
    ...
    ...
}); // <-- Remove `]` from here

var app = angular.module("myApp", []);

app.service('hexafy', function() {
  this.myfunc = function(num) {
    return num.toString(16);
  }
});

app.controller('myCtrl', ['hexafy', '$scope', '$interval',
  function(hexafy, $scope, $interval) {
    $scope.time = new Date().toLocaleTimeString();
    $interval(function() {
      $scope.time = new Date().toLocaleTimeString();
    }, 1000);
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
    {{ time }}
    <br />
  </div>
</body>

关于javascript - AngularJS 中的 $injector.unpr 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685341/

相关文章:

javascript - 匹配除两个特定字符串之外的任何内容

javascript - Draft.js 编辑器组件不可编辑

javascript - 作为 IIFE 一部分创建的 DOM 元素会发生什么

javascript - 如何在vue js中首先选择一个时间并在所有日子中使用它?

AngularJS 路由不断重定向回自身,就像它在循环中一样

javascript - 两个带有按键排序的独立对象的 ng-repeat

javascript - 如何将此内联 javascript 转换为导致冲突的 jQuery 函数?

javascript - angularjs ng-repeat 依赖于另一个 ng-repeat

javascript - 如何在 AngularJS 的路由 Urls 中传递参数

javascript - D3JS 的 AngularJS 指令是否存在?