Unlocking the parent scope in a custom attribute directive

I am new to utilizing angular js.

I came across a similar inquiry on How to access parent scope from within a custom directive *with own scope* in AngularJS?

However, the solution provided did not work for my basic test.

Here is the sandbox. http://jsfiddle.net/VJ94U/1364/

angular.module('mod', []).
directive('myBind', function() {
  return {
    restrict : 'A',
    scope : {
      scopeVar : '@'
    },
    link : function(scope,element,attr){
      element.attr('ng-bind', scope.scopeVar);
      element.text(scope.scopeVar);
    }
  };
});


var app = angular.module('app', [ 'mod' ]);
angular.element(document).ready(function() {
  angular.module('app').run(function($rootScope){
    $rootScope.scopeVar = 'This is scope variable.';
  });
  angular.bootstrap(document, ['app']);
});

I simply need my own my-bind (similar to ng-bind)

Therefore, when the value of the attribute my-bind is the name of a certain scopeVariable, the content within the div should automatically update with the new value of that scope variable.

Unfortunately, I am unable to access the parent scope variable or have the corresponding text displayed within the element.

PS: I understand that I should have used =, but I am still familiarizing myself with @. Please verify the ability to locate the scope variable and utilize its value. PS: I also aim to avoid using $parent

Answer №1

To create a custom directive for binding in Angular, you can follow this example:

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="customVar"><br>
  <div my-binding data="customVar"></div>
</div>

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.customVar = "Custom text";
  }])
  .directive("myBinding", function(){
    return {
      template: "<p ng-bind='bindVar'></p>",
      scope: {
        bindVar: "=data",
      }
    }
  });

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

Unforeseen anomalies arise when deleting an element from an array in a React application

I've been scouring for a solution, but I could really use some human guidance. I have a basic form where users can input additional fields. They also have the option to delete irrelevant fields. The problem arises when trying to remove these fields. ...

I'm having difficulty mocking a function within the Jest NodeJS module

I have a module in NodeJS where I utilize a function called existsObject to validate the existence of a file in Google Storage. While testing my application with Jest 29.1.2, I am attempting to create a Mock to prevent the actual execution of this functio ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...

Is it possible to organize and filter a dropdown menu in JQuery based on a secondary value (new attribute)?

Can the drop-down list be sorted by value2? <select id="ddlList"> <option value="3" value2="3">Three</option> <option value="1" value2="1">One</option> <option value="Order_0" value2="0">Zero</option> </sele ...

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

Encountering status code 0 when handling 413 (Request Entity Too Large) error in AngularJS with Loopback API

1. Revealing Some Details In my client-side application built with AngularJS 1.3.15, I am utilizing a loopback API for handling requests. Within the application, I have set up interceptors using $httpProvider.interceptors to interpret status codes and di ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

The visibility feature in knockout.js appears to be malfunctioning

I am relatively new to using knockout.js and I'm attempting to control the visibility of a label on a slider item based on a specific condition. Even when the condition is false, the label still appears. Any suggestions would be greatly appreciated. ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

Is there a way to ensure that clicking a link_to only opens a partial once?

These are the files I am working with: _comment.haml %div.comment{ :id => "comment-#{comment.id}" } %hr - if current_user && current_user.id == comment.user_id || current_user && current_user.id == reel_user = link_to " ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Implementing AngularJS material design aesthetics to programmatically generated elements

I am working on an AngularJS application and I have a requirement to dynamically add AngularJS material components using Jquery upon clicking a button. While the components are successfully being added to the layout, the styles are not being applied to th ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

Issue with Angular.forEach loop malfunctioning

Here is the code for my custom filter that includes a parameter called viewbookoption, which is a dropdown value. Depending on the selected value from the dropdown, the data will be displayed in a grid. I have used a forEach loop in this filter, but it see ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Initiate an AJAX call

Hey there, I have a piece of code that I need some help with. <button onclick="sbt()" name="step1[save]" type="submit" class="btn-type5 next-btn-form pie" value="Далее">Send</button> function sbt(){ var phone = document.getElementById(&ap ...