Is it possible to bind a directive's scope in both directions, or is it only one-way bound?

My goal is to achieve two-way binding of a directive's scope in a simple manner. Essentially, I have a Parent controller named ParentCtrl with $scope.name='Foo', and a directive with scope: {name: '='}. I expect that if I change scope.name='Bar' within the directive's link function or $scope.name='Bar' from the directive's controller, the template for ParentCtrl should reflect the new value of $scope.name. However, it seems like it's only one way bound from the parent scope to the directive's scope. Am I overlooking something? You can see the issue illustrated in this Plunker link:

http://plnkr.co/edit/VeGvWV2AGftFHF0LhnBY?p=preview

Here's the code:

angular.module('docsSimpleDirective', [])
  .controller('ParentCtrl', ['$scope', function($scope) {
    $scope.name = "Bernie Sanders";
    $scope.occupation = "Arsonist";
  }])
  .directive('myCustomer', function() {
    return {
      template: 'Name: {{name}} Occupation: {{occupation}}',
      scope: {
        name: '=',
        occupation: '='
      },
      link: function(scope, element, attrs) {
        scope.name = "Donald Drumpf";
        scope.occupation = "Fascist pig";
        scope.$apply();
      }
    };
  });

Template used:

<body ng-app="docsSimpleDirective" ng-controller="ParentCtrl">
  Name: {{name}}, Occupation: {{occupation}}<br />  

  <div ng-controller="ParentCtrl">
    <div my-customer name="name" occupation="occupation"></div>
  </div>
</body>

Answer №1

The issue arises from having multiple instances of the ParentCtrl. The first instance is on the body, followed by another one within an inner div.

By declaring the name as a primitive type in the scope variable, any changes made inside the inner controller will result in a new reference for the $scope.name value. This is because prototypal inheritance only applies to objects, not primitive type variables.

It is important to adhere to the dot rule when defining ng-models on the page.

Additionally, there is no need to run the digest cycle inside the directive link function, as this will likely lead to errors. It should be removed from that section.

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

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

Pre-Render Conditions in React - Optimizing Your Components for Faster

Before launching my React application, there are two key conditions that need to be checked: First, it is important to verify if the user is logged in. If not, the user should be redirected to the login page. Secondly, all user settings must be retrieved ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

I attempted to use the Stripe API, but it seems to be non

I seem to be encountering an issue with the stripe.customers.create. My goal is to create a new Stripe customer using the email address of the current user, and then update my user with the generated customer.id. Despite the fact that stripe.customers.cre ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

What is the best way to display changing data in a React component?

Having some trouble with printing data based on the length of an array. Here is my attempted solution, but unfortunately, it's not working as expected. I believe the issue lies in the cb function within the forEach loop. Below is the code snippet: fun ...

Could there be an issue with my website's bootstrap where badges are not being applied properly?

Currently, I am in the process of learning ReactJS and running into an issue where my bootstrap is not working within my .jsx file. Despite following a tutorial (MOSH) diligently and extensively researching on stack overflow, I have not been able to find a ...

I'm looking to learn how to efficiently write file chunks from a video upload in Node Js. How can I

My current project involves attempting to stream webcam or audio data to Node.js and save it on disk. The aim is to send the chunks of data to the server as soon as they are available. I have successfully captured the stream using getUserMedia, set up me ...

When a React Router link is activated, the React Bootstrap dropdown remains open instead of closing as expected

<NavDropdown className="userDropdownButton" title="dropdown" id="user-nav-dropdown" alignRight > <div className="userDropDown"> <Link to="/user" className="userDropDownheader"> user </Link> </div> < ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Using jQuery to measure the height of a div consistently shows a value of 1

I'm attempting to retrieve the height of a specific div using the following code: var divHeight = $("#myDiv").height(); referencing information from the JQuery documentation <div style="width: 300px; height: 300px;"></div ...

Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a t ...

Utilizing Dropwizard for hosting static HTML files

I'm in the process of developing an application using dropwizard and angularjs. I have configured my AssetsBundle as follows: bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html")); The challenge I am facing is that I want multiple page ...

Using jQuery UI to trigger Highlight/Error animations

Apologies if this question seems obvious, but I can't seem to find a clear answer anywhere... Is there a way to add a highlight/error message similar to the ones on the bottom right of this page: http://jqueryui.com/themeroller/ by simply using a jQu ...

AngularJS and ASP.NET MVC showcasing an image file

Can someone please assist me? My Controller is not able to receive Image Files from Angular. Below is my angular file: https://i.sstatic.net/jpNdq.png And here is my Controller: https://i.sstatic.net/4G9vB.png Class Product: public class Product { ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Empty req.params in nested ExpressJS routers

I have a unique routing system that relies on the directory structure of my 'api' folder to automatically configure routes. However, I encountered an issue where the req.params object is undefined in the controller when using a folder name as a r ...

Get the base64 encoding of a File object by utilizing the FileReader.readAsDataURL() method

Currently, I am facing an issue with converting a JS File object into a base64 value and returning that value within a JSON object. My approach involves using FileReader.readAsDataURL(), however, due to the asynchronous nature of this process, it appears t ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...