Utilizing Services in Angular js to Interlink Functions Between Controllers

I have a factory in my code where I store reusable functions for different controllers.

However, when I try to call these functions using ng-click from each controller, it doesn't seem to work as expected.

Is there a more efficient way to handle such scenarios?

view:

<body ng-app="MyApp">
    <div ng-controller="MyCtrl" ng-click='hidepop()'>
        <ul ng-repeat="user in users">
            <li>{{user}}</li>
        </ul>
        <div class="nested" ng-click='showpop()' ng-controller="AnotherCtrl">
        </div>
    </div>
</body>

controller:

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

app.factory("UserService", function ($window) {    
    var root={};
    root.showpop = function () {     
        alert("f")
    }     
    root.hidepop = function () { 
        alert("d")
    }      
    return root;
});

app.controller("AnotherCtrl", function($scope,$location, UserService) {
    $scope.alerter = UserService;        
    $scope.showpop(){
        $scope.alerter.showpop();
    }
    $scope.alerter.hidepop();    
});

app.controller("MyCtrl", function($scope, UserService) {
    $scope.alerter = UserService;
    $scope.alerter.showpop();
    $scope.alerter.hidepop();
});

Check out my fiddle here: fiddle link

Answer №1

I made some adjustments to your code in order to demonstrate a potential usage of the service you are developing - check it out at http://jsfiddle.net/p8LNR/2/ :

HTML:

<body ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <ul ng-repeat="user in users">
            <li>{{user}}</li>
        </ul>
        <div class="nested" ng-click=showpop() ng-controller="AnotherCtrl">
        </div>
    </div>
</body>

Javascript:

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

app.factory("UserService", function() {
    var users = ["Peter", "Daniel", "Nina"];
    var root={
        'showpop':function () { 
            alert("f")
        },
        'hidepop':function () { 
            alert("d")
         },
        'users': users
    };
    return root;
});

app.controller("AnotherCtrl", function($scope,$location, UserService) {
    $scope.showpop = function(){
        UserService.showpop();
    }
    $scope.hidepop = function(){
        UserService.hidepop();
    }
});

app.controller("MyCtrl", function($scope, UserService) {
  $scope.users = UserService.users
});

Some tips for improving your code:

  • Remember that Angular is just a tool for building JavaScript applications, so keep things simple and focused.
  • When working with services, think of them as persistent Javascript objects that can be used throughout your code.
  • If you're planning on modifying the DOM (e.g., creating popups), consider utilizing Angular's capabilities like ng-style to manipulate HTML elements.
  • For more advanced functionality, consider creating custom directives - they can offer more flexibility and reusability.
  • And lastly, pay attention to code formatting for better readability and maintainability in the long run. Consistent spacing and indentation can make debugging easier later on. :)

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

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

Tips on using URL parameters for a successful HTTP GET method in a Sails.JS controller

In my Sails.JS controller, I need to handle URL parameters like this: localhost:1337/api/test/[value1]/[value2] How can I configure the controller to work with these specific URL parameters? I attempted using :value! or something similar such as localhost ...

What is the best way to prevent an HTMLCollection from automatically updating?

Is there a way to prevent the HTMLCollection from being live? var cells = someTable.getElementsByTagName('td'); I noticed that it's a live collection, so when I add a new td to the table, the cells length increases by 1. How can I make it ...

Using the $http.post function in AngularJS to pass an array of objects is not successful

I need to send an array of objects from my main merchandise.php file to another PHP file called process_cart.php using the AngularJS $http.post method. I plan to use a foreach loop in the receiving file to display the contents of the cart. Below is how my ...

HTML mobile buttons showcase

I have been developing an incremental game using HTML, CSS, and JS. The issue I am facing is that the buttons for buildings and other clickable features appear properly on a laptop or desktop but only display one line of text when viewed on a tablet or pho ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Error: Django Rest Framework - Invalid request

I've been attempting to make an API call to a particular endpoint within my Django project from the frontend. The endpoint I am trying to access is located at /tst/. My goal is to fetch data from this endpoint and use it to populate my webpage. Desp ...

Error: Encountered an unexpected token '<' while working in Angular 8

While following a tutorial on LinkedIn learning, I encountered an error when trying to run my code. The error message Uncaught SyntaxError: Unexpected token '<' is puzzling because I cannot find the '<' character as mentioned in l ...

Load a 3D object or model using three.js and then make modifications to its individual components

Seeking advice on displaying and manipulating a 3D model of a robot arm in a browser. How can I load the model into three.js to manipulate all the sub-parts of the robot arm? Using Inventor, I have an assembly of a rotary motor and a shaft exported as an ...

How can an Angular 4 HTML for loop display a loosely typed object (string) normally but behave differently when the element is extracted directly?

Currently, I am utilizing Angular 4 to create an application that primarily involves presenting data from a database and performing CRUD operations. In my experience with Angular 4, I have noticed that the component's HTML does not handle loosely-typ ...

Expanding the content of a single page by clicking on a separate tab

I have a link on Page A. Page B has two tabs, with the content of tabs 1 and tab 2 currently set to "display:none". I want clicking the hyperlink on page A to automatically open or activate the second tab on page B. I am seeking a solution using JavaScri ...

ng-pattern for requiring whole numbers only with no decimal points

Looking for an ng-pattern to limit the entry of decimals in an input type number field. I attempted using ng-pattern="/^[0-9]$/" but it doesn't display an error when entering values like 1.0, 2.0, 3.0, etc. Example: 2.0 = fail 2 = pass 3.0=fail 3=p ...

Using the ng-click directive with checkboxes in Angular

Angular 1.2: <input type="checkbox" ng-model="vm.myChkModel" ng-click="vm.myClick(vm.myChkModel)"> The myClick function doesn't have the correct state? I'm trying to get the updated state after clicking. ...

How to send cross-domain AJAX requests to RESTful web services using jQuery?

I have been utilizing Jquery Ajax calls to access RESTful webservices in the following manner. The web service is being hosted on a different domain. $.ajax({ type: "GET", url: "url for the different domain hosting", crossDomain: true, ...

Retrieving input field value in HTML through a button press

Feeling stuck trying to incorporate an input field value into an ajax call? Here's the code I have so far for a button and input field combination, but I can't seem to get it working. function submit() { $.ajax({ type: 'POST&apo ...

In AngularJS, the Gantt chart fails to load properly in the UI view

Currently, I am utilizing ui-router in my project and I have a requirement for using a gantt chart. I found the necessary information at this link . However, during implementation, I encountered the following error: Error: [$compile:ctreq] http://errors. ...

Tips for preventing the direct copying and pasting of JavaScript functions

Repeating the process of copying and pasting functions such as loadInitialValue(), loadInitialValue2(), loadInitialValue3(), is quite monotonous. This is the repetitive code snippet that I have been working on (when you click on "Mark as Read," the title o ...

Creating Shapes in Leaflet: A Step-by-Step Guide to Drawing Like a Painter

I am attempting to utilize the plugin https://github.com/tcoupin/leaflet-paintpolygon for image annotation in a multipoint circle shape. Unfortunately, the plugin is not functioning correctly as a result of a bug present in the libraries it relies on. Ar ...

Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation: The HTML Template: <polymer-element name="wc-foo" construct ...

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...