What could be the reason for the lack of controller updates despite changes made to the service

Could someone please help me solve the issue with my code?

I expected that after clicking the button, the text would be updated. However, it seems to not be working as intended.

Any assistance you can provide would be greatly appreciated.

main.js

x = angular.module('app', []);

x.directive("changer", function(myService){
        return {
            restrict: "E",
            template: "<button>click</button>",
            replace: true,
            link: function (scope, elem, attrs) {
                elem.click(function () {
                    myService.item1 = 'updated';
                    scope.$apply();
                })
            }
        }
});


x.service('myService', function () {
    var item = {'item1': 1, 'item2': 2}; 

    return {
        item : item, 
    };
});

x.controller('myController', function ($scope, myService) {
    $scope.item = myService.item;
}); 

main.html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="main.js"></script>
</head>
<body ng-controller='myController'>
    <changer></changer>
    {{item.item1}}
</body>    
</html>

Thank you in advance for your help!

Answer №1

Using 'ng-click' within your directive template is a more efficient and effective approach. Check out the demo below for guidance:

x = angular.module('app', []);

x.directive("changer", function(myService) {
  return {
    restrict: "E",
    template: "<button ng-click='update()'>click</button>",
    replace: true,
    link: function(scope, elem, attrs) {

      scope.update = function() {

        myService.item.item1 = 'updated';


      }
    }
  }
});


x.service('myService', function() {
  var item = {
    'item1': 1,
    'item2': 2
  };

  return {
    item: item,
  };
});

x.controller('myController', function($scope, myService) {
  $scope.item = myService.item;
  $scope.test = "dfsf"
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller='myController'>
      <pre>{{item| json}}</pre>
      <changer></changer>

    </div>
  </div>
</body>

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

Unable to modify the color of UML state elements within JointJS

I need some help with jointjs as I am in the process of adjusting the color of a UML state diagram graph using this command: graph.getElements()[4].attributes.attrs[".uml-state-body"]["fill"] = "#ff0000"; However, despite trying this, the color of the st ...

Transforming Material UI into a class-based component

How can I transform a React function into a class? I'm having trouble understanding how to adjust const { classes } = props; in a function to work within a class. You can find an example button function from Material UI here: import React from &apos ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

Sharing information from Directive to Component in Angular

Here is a special directive that detects key strokes on any component: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[keyCatcher]' }) export class keyCatcher { @HostListener('document:keydo ...

Put emphasis on the input field - React component

My React component features an input field with a disabled attribute. When the component is clicked, the input becomes enabled for the user to type in. I have successfully implemented this functionality so far, but now I need to focus on the input field on ...

How come a colon within a function's body does not result in an error in JavaScript?

During my coding journey, I encountered a situation where I was attempting to return an object from an arrow function. However, I noticed that the code snippet below was simply returning undefined. After some investigation, I determined that the curly br ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

The Ajax Control Upload consistently defaults to the default value and disregards any text input selected from the drop-down list

On my website, I have implemented an ajax control upload event that allows users to upload a zip file and then unzip it using zlib. The folder name for unzipping is created based on the selection from a dropdown list. However, I am facing some issues where ...

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Dynamic loading of XML data into a DIV when hovering over it

The main idea behind my project is quite simple. I have a grid of company logos extracted from an XML document using XSLT, each logo with its own unique link to the respective company profile. On the same page, I have a separate div that serves as a "prev ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Struggling with making JSON.parse() function properly in a Discord Bot

I have a separate JSON file connected like this const Players = require('./Database/Players.json'); and a parser that handles the code client.on('message', message => { if (message.content.toLowerCase() ==='smack activate ...

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

Deliver a numerical input to the component on an equivalent hierarchical tier

I need to find a way to pass the values of the "things" array to another component on the same level in my app. The structure of my app is as follows: sidebar.component data.service body.component In the sidebar component, I have a button that triggers a ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Guide on transforming an array containing indexed objects into a simple object

Can anyone help me with converting an array of this specific type? place: [ { "_id": "xxxxx", "loc": [ 0: "xxx", 1: "xxx" ] } ] Into something ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Display all items that contain a specified string using JavaScript

I'm in need of some assistance with a problem that I've been struggling with. I have several JavaScript objects containing different data pieces as shown below:- Object {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 ...

Updating objects in Angular 8 while excluding the current index: a guide

this.DynamicData = { "items": [ { "item": "example", "description": "example" }, { "item": "aa", "description": "bb" }, ...