What could be causing the lack of updated data on the service coming from the directive?

My current setup involves updating data stored in a service and shared with the controller to display in the view.

The example showcases two variables - one holding an array and the other just a string.

One thing that puzzles me is why does the array get updated and displayed in the view, but not the string?!

JavaScript:

function fooService() {
    var mystring = 'old string';
    var myarray = [];

    var updateArray = function(data) {
        myarray.push(data);
    };

    var updateString = function(data) {
        mystring = data;
    };

    return {
      myarray: myarray,
      mystring: mystring,
      updateString: updateString,
      updateArray: updateArray
    }
}

function MainCtrl($scope, fooService) {
    this.myarray = fooService.myarray;
    this.mystring = fooService.mystring;
}

function fooDirective(fooService) {

    function link(scope) {

      fooService.updateArray(scope.vm.name);
      fooService.updateString('new string');

    }

    return {
        restrict: 'EA',
        replace: true,
        template: '<h2 style="color: {{vm.color}};">{{vm.name}}</h2>',
        scope: {},
        controller: 'MainCtrl',
        controllerAs: 'vm',
        bindToController: {
            name: '@',
            color: '@'
        },
        link: link
    };
}

angular
    .module('app', [])
    .service('fooService', fooService)
    .controller('MainCtrl', MainCtrl)
    .directive('fooDirective', fooDirective);

HTML:

<div ng-app="app">
    <div ng-controller="MainCtrl as vm">
        {{vm.myarray}}
        {{vm.mystring}}
        <foo-directive data-name="Markus" data-color="red"></foo-directive>
        <foo-directive data-name="Nemanja" data-color="green"></foo-directive>
        <foo-directive data-name="Luke" data-color="blue"></foo-directive>
    </div>
</div>

I may have misunderstood, but isn't the purpose of services to store data shared across the app?

See the working example here: http://jsfiddle.net/markus_falk/f00y3tL3/6/

Answer №1

Is it necessary for services to contain data that is shared throughout the application?

That is accurate, but when you

return {
  myarray: myarray,
  mystring: mystring,
  // ...
}

you are actually returning a new object (which becomes your service instance) containing a reference to myarray and a copy of mystring. Therefore, any changes made to myarray within the service will be reflected correctly. However, this will not work for the string (since primitive types are immutable and passed as values), as the service only returns a copy of it.

Instead of trying to modify a string directly (a primitive value), consider using a getter/setter approach.

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

sending Immutable.Map objects as parameters in React components

It appears that the popularity of the immutable library for React is on the rise. However, I'm encountering difficulties when trying to utilize Immutable.Map objects as props. It seems that Immutable.Map doesn't mesh well with the spread operator ...

Can you please explain the differences between "resolved" and "rejected" in a deferred object within jQuery?

Recently, I inquired about a refreshing page solution if an internet connection is available on Stack Overflow. The user @Fabrizio Calderan provided an elegant approach utilizing deferred object implementation: setInterval(function() { $.when( ...

Locate and substitute `?php` and `?` in a given string

I am facing a challenge with inserting a large string of valid HTML code into the DOM, as the string also includes PHP code. When Chrome renders the code, it automatically comments out the PHP sections. The PHP code is encapsulated in <?php ... ?>, s ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Ensure the correct file extension is chosen when selecting a file for the 'file_field' and display any error messages using Ruby on Rails

I am currently using Ruby on Rails 3 and Prototype, and I need to be able to check the file extension when a file is selected with file_field. I only want to allow files with extensions of .doc or .pdf, any other extensions should display an error. In my ...

Issue with Ajax communication to PHP script causing data not to be sent

I am developing a web application that functions as an extensive form which will later be converted into a PDF document. Upon submission of the form, all input data is sent to a PHP file where they are stored as variables to be included in the PDF. Some of ...

Fetching from the same origin results in a null comparison issue due to HTTP CORS restrictions

Encountering an issue where a simple same-origin fetch("fetch.xml") call fails, resulting in a console error message Access to fetch at 'http://127.0.0.1:8000/fetch.xml' from origin 'null' has been blocked by CORS policy: Th ...

Tips for triggering the .click() function upon returning to index.html after visiting a different page

I'm in the process of creating a portfolio website where the index.html page features a sliding navigation bar that displays a collection of projects. Each project is linked to a separate work.html page. I would like the sliding nav to automatically o ...

Unusual problem arises with styling and element measurement (scrollWidth / scrollWidth) in Gatsby framework

Currently, I am working on a component that splits lines based on the parent container's width without overflowing. Despite successfully implementing this in a sandbox or pure react application (even with custom fonts), I encountered issues when using ...

Tips for concealing ion-refresher with ng-if?

Currently, I am working on an AngularJS 1.5.3 and Ionic 1.3.5 app development project. My goal is to conceal the ion-refresher element based on a specific condition: <ion-refresher ng-if="data.state === 'main'" on-refresh="refresh()" s ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Retrieve the Multer file name and/or file path

Just checking in on everyone's well-being. I'm currently struggling to retrieve the file path or name after uploading it to the folder. Whenever I try console logging req.files.path or req.files.filenames, it always returns undefined. Could someo ...

rails neglecting to include in the array

Could someone help me with this block of code I have: doc.xpath("//script[@type='text/javascript']/text()").each do |text| if text.content =~ /more_options_on_polling/ price1 = text.to_s.scan(/\"(formatted_total_price)\ ...

What is the best way to input a value into the search bar within an Iframe?

I've created a basic website using node and a pug page where I inserted an iframe from wikipedia.com. My goal is to have the search input in the Wikipedia iframe populated with a value based on a button click within the same pug page. Is this feasible ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

What could be causing the inability to move down on this page?

Trying to scroll down a page using Selenium with Python and the execute_script command, but encountering issues. Despite executing the code provided below, I am unable to reach the bottom of the page: def create_browser(first_page=None): print "Starti ...

Need help resolving an issue with an HTML header that's overlapping in JavaScript?

Hey there! I was working on implementing a dynamic header that resizes as you scroll on the page. I also decided to try out Headroom as an additional solution, and it seems to be functioning well in terms of hiding the header. You can check out my progress ...

Creating an outlined effect on a transparent image in a canvas: step-by-step guide

Currently, I am working on creating transparent images using canvas in HTML5 and I would like to incorporate borders into them. The issue I'm facing is that the "Stroke" property does not consider the transparency of the image and applies it as if it ...

Express.js: Initial Request Fails to Retrieve Set Cookie

In my Express.js application, I am facing an issue where setting a cookie in one middleware function results in it being undefined when attempting to access it in the following middleware function on the initial request. Strangely, on subsequent requests, ...