AngularJS view not refreshing despite changes made to scope linked with factory

Check out the following code snippet.

Click on the bold hello text. The scope is updated from the factory, but the view does not reflect the changes. I have tried using scope.apply() to update the view, but it doesn't seem to be working as expected. Therefore, I am anticipating the bold text to get updated. Keep in mind that the data in the factory can be modified from anywhere, so simply calling scope.$apply() on the click event won't suffice.

angular.module('myModule', []) 

.factory('myFactory', function($http, $window){
    return { str:'hello' };
})

.directive('mydir', ['$timeout', 'myFactory', function ($timeout, myFactory) {
    return {
        restrict: 'E',
        scope: {},
        template: '<div><b>{{myf.str}}</b>',
        link: function (scope, elem, attrs, ctrl) {
            scope.myf = myFactory;
          
         scope.$watch('scope.myf', function(n, o) {
           scope.$apply();
            
          });
          
             elem.bind('click', function(){
               myFactory.str += '1';
               elem.append(scope.myf.str);
            });
        }
    };
}])
<html ng-app='myModule'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<mydir></mydir>
  

Answer №1

The main issue at play here is the scope change in the click event without it being automatically applied. To fix this, simply move the scope.$apply() to the click handler. Additionally, removing the scope.$watch will prevent any potential digest errors or infinite loops.

In order to better observe the scope changes, I have eliminated the elem.append.

angular.module('myModule', [])

.factory('myFactory', function($http, $window){
    return { str:'hello' };
})

.directive('mydir', ['$timeout', 'myFactory', function ($timeout, myFactory) {
    return {
        restrict: 'E',
        scope: {},
        template:'<div><b>{{myf.str}}</b>',
        link: function (scope, elem, attrs, ctrl) {
            scope.myf = myFactory;

             elem.bind('click', function(){
               myFactory.str += '1';
               scope.$apply();
            });
        }
    };
}])
<html ng-app='myModule'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<mydir></mydir>

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

Encountered an `EPIPE` error during the testing of a POST request with Jest

I have a simple server that is set up to handle POST requests and return a "413 Request entity too large" error if the request body exceeds the allowed size. During my testing with Jest, I've noticed that sometimes the correct error is returned, but m ...

An unexpected error occurred in NodeJS: It is not possible to adjust headers once they have been sent

Recently, I've been working on a nodejs project and encountered the error message "Can't set headers after they are sent" when trying to get a response from http://localhost:8080/api/user. Despite researching solutions on Stack Overflow, none of ...

Guide on incorporating an if-else statement within a React function Return()

Currently diving into if-else statements in React, I'm trying to make the button visible in the table only when the "step" variable is set to 1, otherwise the button (and row) should not appear. What's the best approach to implement this conditi ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

The AJAX call fails to refresh the secondary table in CodeIgniter

I have a situation where I need to display data from two tables - car producer and car model, pulled from a database. My goal is to filter the second table to only show cars from a specific producer when that producer is clicked in the first table. I attem ...

How can I change the name of a variable in an Angular view?

Within my Angular project, there is a specific value in the controller referred to as: $scope.feature1.items.thisItem Repeatedly referencing thisItem within a particular <div> in the view has become cumbersome using {{feature1.items.thisItem}}. Her ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Concealing the nearest div that has a particular class

I'm currently developing an application that simulates desktop-style application windows with the ability to open, minimize, and close. While I have successfully implemented the functionality to expand and collapse these windows, I am facing difficult ...

eliminating various arrays within a two-dimensional array

I need help with a web application that is designed to handle large 2D arrays. Sometimes the arrays look like this: var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]]; I am looking to create a function that will remove any array ...

The functionality of Component OutlinedInput with parameter "notched" and Component InputLabel with parameter "shrim" is experiencing issues in Material UI version 5.15.2

I am facing a unique issue.. In version Material UI 5.15.2, I have created a custom component to handle the display of InputLabel and OutlinedInput based on specific conditions.. Below is an example where I provide certain parameters to guide my component: ...

Tips for adjusting CSS font sizes within a contenteditable element?

I am looking to develop a compact HTML editor using JavaScript that allows me to customize the font-size of selected text with a specific CSS value. The documentation states that the FontSize command is used like this: document.execCommand("FontSize", fal ...

Creating an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

Implementing the cryptocoins-icons npm package in your AngularJS application for enhanced icons

Currently in the process of creating a custom website using a template called blur-admin, which can be found at https://github.com/akveo/blur-admin Being new to npm, I decided to incorporate a npm package called cryptocoins-icons into my project. Followin ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

Utilizing ngClass With Directive Selectors in Angular 2

I am currently working with the latest Angular 2 beta version (45?) and I am facing an issue when trying to apply an ngClass to the element specified by the directive selector. The variable used to toggle the class seems to not update. My suspicion is tha ...

Node.js applications on Openshift frequently encounter 503 errors

I am currently in the process of setting up my initial Node.js + express web application utilizing Openshift's complimentary service. After installing node + npm and Openshift tools on my computer, I attempted to run my application. It functions perf ...

An issue has occurred: TransformError SyntaxError: Unexpected keyword 'const' was encountered

While practicing programming with React-Native, I encountered a problem that I couldn't figure out how to solve. I attempted to use solutions from various forums, but none of them worked. import { StyleSheet, Text, View, Image } from 'react-nativ ...

In what way does the map assign the new value in this scenario?

I have an array named this.list and the goal is to iterate over its items and assign new values to them: this.list = this.list.map(item => { if (item.id === target.id) { item.dataX = parseFloat(target.getAttribute('data-x')) item.da ...

Customize ng-repeat lists by filtering elements based on another ng-repeat list

With only one array displaying titles, descriptions, and categories, the challenge arises when users can add their own categories. To showcase all categories and items, I utilized ng-repeat. The aim is to filter items using two filters: a text input for ti ...