Modify the parent scope variable within an Angular directive that contains an isolated scope

Here is a directive implementation:

<some-directive key="123"></some-directive>

This directive code looks like this:

angular.module('app').directive('someDirective', ['someFactory', '$compile', '$timeout', function(PatientFactory, $compile, $timeout){

    return {
                scope: {

                    customer: "="
                },
                controller: _controller,
                templateUrl: 'components/sometemplate.html',
                link: function (scope, element, attrs) {   


                }
            };

There is another directive based on the key attribute. It retrieves the customer data, sets it as an attribute, then recompiles but encounters issues.

angular.module('app').directive('key', ['someFactory', '$compile', '$timeout', function(PatientFactory, $compile, $timeout){
     return{

                link: function(scope, el, attr){

                    //if key is provided, fetch the customer based on the key.
                    if (attr.key) {                        
                        scope.someFactory.getCustomerByKey(attr.key).then(function (res) {    

                            el.attr('customer', res);                            
                            var fn = $compile(el);
                            return function(scope){
                                fn(scope);
                            };

                        });

                    }else{

                       //error

                    }


                }

The customer data appears to update in the $parent scope according to the dev console, but the view displays {{customer}} instead of the actual customer details.

Answer №1

Make sure to use scope.$apply after using $compile.

To learn more, check out this helpful answer: Why is it important to call scope.$digest() after $compile(element)(scope) in unit testing?


LATEST UPDATE

Another issue could be related to the priority. According to the Angular documentation, make sure to set the priority of the key directive higher than that of some-directive so that user data is accessible during the execution of the link function of some-directive.


UPDATE 2.0

I suggest implementing the desired functionality (such as calling the factory based on a key) within the controller of the directive itself. For a practical example, take a look at this plunker: https://plnkr.co/edit/BH3bDD?p=preview.

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

Create a Vue3 Component without attaching it to the DOM

Let's consider creating a Vue3 component in the following way: import { defineComponent } from "vue"; var instance = defineComponent({ computed:{ message() { return 'Hello world' } } }) To instantiate it and ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Create your own custom block on the frontend product page

I am trying to create a custom block on the Product Page of my Magento store. I attempted it like this: Magento- How can i add a new custom block in product details page using module Unfortunately, it did not work as expected. Did I make any mistakes he ...

Remove the array element if the value is blank

I have an array with different objects, and I need to efficiently delete the entries where the name is empty, similar to the first and third object in the example below: var myArray = [ { "Name": "", "Value": "" }, { "Name": "aaa", "Value": "bbb" ...

Automatically submit upon selecting an option

Encountering some difficulties with the code provided below. Purpose of this code I have multiple list items (shown here is just a snippet) made up of select elements, options, and one submit input field. When an option is chosen, the user can click on ...

What is the proper way to specify a file destination in React?

After reading this article on downloading objects from GCP Cloud storage bucket, I'm curious about setting the file destination dynamically in React. Is there a way to achieve this? The article can be found at: https://cloud.google.com/storage/docs/do ...

Utilizing HTML5/JavaScript to send a text message from a mobile device

I am developing a mobile web application to be downloaded from various markets with a mini web server, capable of running on any operating system such as iOS, Android, Windows8, and more. My goal is to make the application as OS-independent as possible by ...

Angular - connecting a function directly

Is there any potential performance impact of directly binding a function in directives like ng-show in AngularJS? <div ng-show="myVm.isVisible()"> .... </div> // controller snippet (exposed through controllerAs syntax) function myCtrl (myServ ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Passing the AngularJS ng-model from a template to a directive's controller

I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService Here is a snippet of how my directive looks: app.directive('appComments', function( CommentService ) { r ...

When React first fetches data and users move to chat with each other, the state value does not update

Recently, I started learning about React and Node.js as I dive into building a chat application. When a user is clicked for one-on-one chat, I retrieve records from the database using backend Node.js and also incorporate socket.io. In my Chat.js file: imp ...

unable to assign the disable property to a button element

In the code snippet below, I am working on a child-component. I have created a button and I want to include a disable property. However, the current implementation of the code results in an error message with red underlining indicating: Type '"is ...

When attempting to access AJAX JSON properties using an index within a promise, the result returned is undefined

I have a quiz app that communicates with my server's API using MongoDB. I am trying to access the response indexes in this way: setTimeout(() => { axios.get('/api/ninjas') .then(function (questions) { var data = questions.d ...

Using Three.js, generate a series of meshes that combine to create a seamless 90-degree donut shape

I'm on a quest to discover an algorithm that can create the following shape in Three.js. Here is my rough sketch of the expected shape The number of meshes needed to form the 90 degree donut, as well as the thickness and spacing between them, should a ...

Understanding the reasons behind 'undefined' res.body in Express

Why does the response body show as undefined in Express? How can I access the response body properly? Is something going wrong here? import {createProxyMiddleware} from 'http-proxy-middleware' import bodyParser from 'body-parser' impor ...

In React, I am currently working on implementing a feature that will allow the scene camera to move as the user scrolls

I'm currently working on incorporating a feature to enable movement of the scene camera when scrolling in React. However, as I am relatively new to using this library, I am unsure which implementation approach would be most suitable for achieving this ...

Exporting a function to another class using the default export is a common practice

I'm working with two classes, Orders.js and api.js. In api.js, I need to invoke a function called ShowAlertWithDelay. However, due to the existence of a default export named mapStateToProps, I am unable to declare another export. Below is the code sni ...

Obtain distinct values from an array of dictionaries and form a new dictionary

Looking at the JSON data provided below: [{ "name": "Il Brigante", "rating": "5.0", "match": "87", "cuisine": "Italian", "imageUrl": "/image-0.png" }, { "name": "Giardino Doro Ristorante", "rating": "5.0", "match": "87", ...