The issue with the application of the scope.apply attribute directive arises when it is applied within an

I am currently utilizing an attribute directive in order to update the DOM with a variable named profileImage. The directive, known as ppt-profile-icon, functions correctly except when placed within an ng-repeat. Despite scouring through numerous queries on Stackoverflow, I have yet to find a solution.

Below is the HTML code:

<div class="img-preview" ng-style="{'background-image': 'url(' + profileImage + ')'}"></div>


<ul class="dropdown-menu pre-defined-icons" uib-dropdown-menu role="menu" aria-labelledby="single-button">
    <li ng-repeat="predefinedImage in vm.predefinedImages">
        <a>
            <img ppt-profile-icon src="{{predefinedImage}}" width="100%" />
        </a>
    </li>

    <!--This works fine outside of the ng-repeat-->
    <li>
        <a>
            <img ppt-profile-icon src="content/img/people/noProfileIcon.svg" width="100%" />
        </a>
    </li>
</ul>

And here is my custom directive:

angular
    .module('app.core')
    .directive('pptProfileIcon', function ($timeout) {
        //link function for DOM manipulation
        function linkFunction(scope, elem, attrs) {
            elem.bind('click', function () {
                scope.profileImage = attrs.src;
                scope.$apply();
            });

        }//end

        //Directive Declaration
        return {
            restrict: "A",
            controller: ['$scope', function ($scope) {
                //sets environment
            }],
            link: linkFunction
        }//end

    });//end

Within my link function, I have attempted:

attrs.$observe('src', function (val) {
    $timeout(function () {
        scope.profileImage = val;
        scope.$apply();
    });
});

$timeout(function () {
    scope.profileImage = attrs.src;
    scope.$apply();
});

Answer №1

A common issue is that the `scope` in your directive refers to the scope of the `ngRepeat` directive, not the parent scope. This means that you are only modifying the `profileImage` within the repeater.

One solution would be to use an executable binding like this:

.directive('pptProfileIcon', function() {
	return {
		restrict: 'A',
		scope: {
			pptProfileIcon: '&'
		},
		link: function(scope, elem) {
			elem.on('click', function() {
				scope.pptProfileIcon({
					profileImage: elem.prop('src')
				});
				scope.$apply();
			});
		}
	}
})

After that, you can create a function in your controller's scope to handle setting the image:

$scope.setProfileImage = function(image) {
	$scope.profileImage = image;
};

Then, update your template accordingly:

<img ppt-profile-icon="setProfileImage(profileImage)" ng-src="{{predefinedImage}}" />

For a demo, you can check out this Plunker link ~ http://plnkr.co/edit/GqFXqZW5AmLCyWHblBDN?p=preview

Answer №2

It is recommended to always use objects in your ngModels when working with parent-child scopes. Simply adding vm.model before primitives should suffice. For more information, refer to this link.

<div class="img-preview" 
     ng-style="{'background-image': 'url(' + vm.model.profileImage + ')'}"></div>

When dealing with the link function:

//link function for DOM Manipulation
function linkFunction(scope, elem, attrs) {

    elem.bind('click', function () {
      scope.vm.model.profileImage = attrs.src;
      scope.$apply();
    });

}//end

View the plunker example here: Plunker Example

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 with jQuery modal not adjusting its height properly

I am a jquery modal popup newcomer. I can open the modal when clicking on the hyperlink, but I'm having trouble with the height setting. Despite my attempts and searches online, I couldn't figure it out. When trying to post a question about the & ...

The focus functionality in Angular seems to be malfunctioning

Having trouble with simple focus in Angular <div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();"> html <input type="text" data-ng-model="mod ...

The property express.json() is not recognized

Why doesn't Typescript recognize the express.json() function, even though many tutorials claim it should compile without errors? Could I have overlooked something in my code? An example tutorial that suggests this code works: https://auth0.com/blog/n ...

What is the best way to retrieve the data from this JSON response generated by the Wikipedia API?

Trying to work with the Wikipedia API using jQuery and encountering some challenges. Here is the code snippet I'm working with: var apiurl = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&exp ...

Is there a way to distinguish between a request from prerender.io (crawlers) and a real user (browser) using JavaScript?

I needed to identify whether requests were coming from prerender.io (a library used for rendering AngularJS applications for web crawlers) or from real users. If the request was from prerender, I had to redirect to a page specifically designed for SEO purp ...

Troubleshooting issue with password validation not functioning correctly within the Joi schema in React

I am working on developing a password change form using React. Below is the code snippet of my component: import React, { Component } from "react"; import Joi from "joi-browser"; import "./Login/Login.css"; import { UAA } from ...

granting authorization to modify content post channel establishment in discord using discord.js

I am encountering an issue with granting the message.author and staff permission to view the channel right after its creation. The problem arises when the channel's parent (category) is changed, causing it to synchronize with the permissions of the pa ...

Communicating with my own account through Nodemailer

I have successfully set up nodemailer locally to handle email functionalities on my website. The goal is for it to extract the user's email input from an HTML form and then forward it to my Gmail account through a contact form. <form action="http: ...

I am attempting to activate the HTML5 color picker's popup using JQuery

Is there a way to open a color picker in a popup window when an input[type=color] is clicked, using JavaScript? HTML <div id="customColorPick"></div> <input id="customColorPickInput" type="color" /> JQuery $("#customColorPick").click( ...

Add HTML content individually to each item in the array

I am currently developing a plugin and I need to load a preset in order to populate a form with the relevant data. In an attempt to write concise code, I created a variable called "template" that looks like this: var Fields = '<div c ...

Exporting a variable to multiple files for use as a string property

My goal is to send a base URL to each file, which will be combined with the existing full path stored as a property in another object. However, I encounter an error message indicating an invalid URL when attempting to use the path. Here is the setup on th ...

Implementing various distinct string substitutions based on the specified character beginning and end positions

I have a string of text: Google is a search engine created by Larry Page and Sergey Brin. Within this string, there are certain named entities stored in a nested array. Here's what the array looks like: [["Google","ORG",0,5],["search engine","PRODU ...

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...

Is there a way in PHP to retrieve database values and display them in HTML text boxes when a button is clicked, all without

Is there a way to dynamically fetch values from a database and display them in text boxes without the need to refresh the page? Here is the PHP code snippet I have been working on: <?php include 'Connection.php'; $sql = mysqli_query($conn ...

The XML parser from a third-party (xpath.js) is throwing an error stating "Uncaught end tag name: div does not match the current start tagName"

Looking to extract data from a webpage for my iOS app using parse.com's cloud code backend. I already have the web scraping functionality implemented in iOS, but now want to transition it to the backend using a node.js library named xpath.js Parse.Cl ...

Received an empty string after passing the "_id" parameter in mongoose

I am currently developing a task management app using node js, express, and mongoose. My current focus is on implementing the delete item functionality by utilizing a checkbox in a form to pass the item._id to express. This is how my data type for to-do ...

Error: Typically encountered when trying to bind a live event to an undefined object

While developing an application in PHP with AJAX functionality, I encountered a problem specific to Internet Explorer (tested on version 8.0.6001.18702). However, the application works perfectly fine on browsers like Firefox, Chrome, and Opera. The specif ...

Troubles with retrieving Array data for a JavaScript column chart

I am currently developing a Flask app in Python and utilizing render_template to send back 2 arrays, "names" and "deals", to my HTML file. I have confirmed that these arrays are working correctly based on the code snippet below that I tested, which display ...

The placement of the JavaScript OnChange Listener within an HTML document.LayoutControlItem in HTML

I'm facing issues with the OnChange listener not working as expected. When I place the script after the </form> tag, it works fine. However, if I put the script within the <head> tags, it fails to function properly. Due to limitations on ...

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...