AngularJS中的$injector.unpr错误

$injector.unpr error in AngularJS

本文关键字:unpr 错误 injector 中的 AngularJS      更新时间:2023-09-26

我是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>

缩小代码并保留参数映射时使用数组语法。关于这方面的更多信息,请参阅我的另一个答案为什么我们在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>

Tushar的建议是完美的,只是添加了Plunker 的工作部件

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