What is the process of building a service in AngularJS?

I have written this code using a service in angular.js. Upon running the code, I encountered an error Uncaught Error: [ng:areq].

</ons-toolbar>
        <div ng-controller="testAppController">
          Search: <input ng-model="query" type="text" class="text-input" id="my-input"/>
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
      </tr>
      <tr ng-repeat="country in countries | filter:query">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
      </tr>
    </table>
 </div>

 <div ng-include='"partials/footer.html"'></div>
    </ons-page>

demo.js

angular.module('testsapp',[])
  .service('helloworldservice',function($http){
     this.getDatafunction = function(){
        $http.get('json/countries.json')
          .success(function(data) {
             alert("sucesss");
          })
          .error(function(data) {
            alert("wrong");
          });     
     }
  })
  .controller('testAppController',['helloworldservice',function($scope,helloworldservice){
     helloworldservice.getDatafunction();
  }]);

Answer №1

here

 .controller('testAppController',['helloworldservice',function($scope,helloworldservice)

you should update it to

.controller('testAppController',['$scope','helloworldservice',function($scope,helloworldservice)

for more information, please refer to

https://docs.angularjs.org/tutorial/step_05#a-note-on-minification

angular.module('testsapp', []).service('helloworldservice', function($http) {
  this.getDatafunction = function() {
    $http.get('json/countries.json').
    success(function(data) {
      alert("sucesss");
    }).
    error(function(data) {
      alert("wrong");
    });
  }

}).controller('testAppController', ['$scope','helloworldservice',
  function($scope, helloworldservice) {
    
    helloworldservice.getDatafunction();
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <body ng-app="testsapp">

        <div ng-controller="testAppController">
          Search: <input ng-model="query" type="text" class="text-input" id="my-input"/>
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
      </tr>
      <tr ng-repeat="country in countries | filter:query">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
      </tr>
    </table>
 </div>

 <div ng-include='"partials/footer.html"'></div>
    
  </body>

Answer №2

Make sure to include the $scope service name in your controller definition:

.controller('testAppController', ['$scope', 'helloworldservice', function($scope, helloworldservice){
   helloworldservice.getDatafunction();
}]);

It's important to remember that when specifying service names as strings for the parameters, you need to list all parameters for the function. This practice is recommended especially when minifying JavaScript code.

Following this approach, it would be a good idea to also specify the $http parameter in your service definition:

.service('helloworldservice', ['$http', function($http){
  this.getDatafunction = function(){
    $http.get('json/countries.json')
      .success(function(data) {
         alert("Success");
      })
      .error(function(data) {
        alert("Error");
      });     
  }
}])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies direc ...

Using Android to retrieve and process JSON data for display in a list view

I have a current android project where I am trying to implement a functionality that allows me to display user data into a listview on another activity by pressing only one button. Currently, my solution involves pressing two buttons - one to retrieve JSON ...

Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before. Let's assume the controller has these variables: $scope.valueArr = ['Hello', 'No', 'Yes']; $scope.myValue = 'Hello'; And there is an ng-repeat as follows: ...

The data from the Ajax request failed to display in the table

JavaScript Code</p> $(function (){ $.ajax({ type : 'GET', url : 'order/orders.json', dataType : 'JSON', success: function(data) { /*var trHTML = ''; $.each(orders, function (i, it ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

React's createPortal function does not place the child element inside a container

My new to-do list app in React has a simple functionality where clicking a button should add a new item to the list. However, I am facing an issue with the createPortal method not triggering the UI to render the new item. Here's the code snippet causi ...

ContainerView: challenges encountered when dynamically inserting views

ContainerView.pushObject() does not automatically connect dynamically added views with a Container object. The absence of an auto-wired container leads to a rendering error when a view renders a template containing a handlebars render helper. SIMPLE SCENA ...

Create a Vue component that utilizes the v-for directive to iterate through a list of items, passing data from a

Imagine having two arrays with a similar structure like this: const individuals = [{name: "Jane Doe", id: "0001"},{name: "John Doe", id:"0002"}, {name: "Sam Smith", id: "0003"}, {name: "Joe ...

Issue with function execution in MVC after invoking from jstree

My jquery code is supposed to trigger the MVC function call: $(document).ready(function () { alert("ddddd"); $("#divJsTreeDemo").jstree({ "plugins": ["json_data"], "json_data": { "ajax": { "type": "POST", "url": "/W ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Utilizing AJAX to send an array of data in JSON format

I have successfully extracted specific elements from a form, stored them in an array and now want to convert this array into a JSON object to send it to a PHP file via AJAX. However, I am facing some issues with my code. Here's what I have done so far ...

Spin the item around the axis of the universe

My goal is to rotate an object around the world axis. I came across this question on Stack Overflow: How to rotate a object on axis world three.js? However, the suggested solution using the function below did not resolve the issue: var rotWorldMatrix; / ...

Is there a way to include a Spring Security JSESSIONID while utilizing SockJS and STOMP for cross-domain requests?

Currently, I am facing an issue with my setup which involves 3 different use cases - two of them are functioning properly while the third one is not. The configuration includes an AngularJS client using SockJS with STOMP. The backend is a Spring applicati ...

"Troubleshooting: Why is my Bootstrap modal window only printing a

I've encountered an issue with printing the content of a Bootstrap modal window. Previously, the code I had was working fine but now it seems to be malfunctioning. Content is dynamically added to the form using appendChild() in a separate function. Ho ...

Yeoman Error: Issue with 'mkdir' in Javascript Execution

Currently, I am in the process of setting up a Meanjs instance using a Yeoman generator. However, when I execute 'sudo yo meanjs', everything goes smoothly until an issue arises while attempting to create a directory and it fails. Any insights on ...

ui-router: Issue with ui-sref causing font color to remain unchanged

I've been trying to customize the font color of a navigation link using ui-router's ui-sref functionality, but I'm facing an issue. While I can change the background color by adding it to the .active class in my CSS, the font color remains u ...

ngOptions compare by actual value

My webserver (node.js) serves a JSON file with a list of languages in the format: { "en" : "English", "fr" : "French" } and a separate JSON settings dictionary like this: { "currentLanguage" : "en" }. The select statement is as follows: <select ng-opti ...

Creating a query string using a jQuery array that contains multiple values for a query variable

After writing some code to convert an array into a filter string, I noticed that the generated string was not in the format I wanted. product_size=123&product_size=456 Instead of this, I needed it to be product_size=123+456. To achieve this, I reali ...

Learn the process of utilizing Javascript to substitute additional texts with (...) in your content

I am facing a challenge with a text field that allows users to input text. I want to use JavaScript to retrieve the text from the textbox and display it in a paragraph. However, my issue is that I have set a character limit of 50. If a user exceeds this li ...