0

I am new to AngularJS JavaScript. Just started learning it. I was trying with some small sample programs. Here is what I tried but its throwing error.

<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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
user3714162
  • 89
  • 2
  • 7

2 Answers2

1

The array syntax is used when the code is minified and keep the mapping of arguments. For more on this please see my other answer Why we Inject our dependencies two times in angularjs?.

In the code, as there is no parameter passed to the hexafy service, there is no need of using the array syntax and pass empty string.

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

Use normal syntax.

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>
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

What Tushar has suggested is perfect, Just adding working piece of Plunker

app.service('hexafy',function() {
  this.myfunc = function(num) {
    return num.toString(16);
  }
 }
);
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • `Just adding working piece of Plunker`, should it be added as new answer? Tushar has already added working example. – Khalid Hussain Apr 18 '16 at 04:31
  • @KhalidHussain Yes. This answer shows the correct code, a working example. Also, he has added attribution. – Tushar Apr 18 '16 at 04:33