AngularJS directive with a private scope

I am currently working on a directive and controller setup, which I have mostly learned from the Angular JS Directives PacktPub book.

angular.module('myApp',[])
.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };
})
.controller('MyCtrl', function($scope){
    $scope.title = "Hello World";
    $scope.setAppTitle = function(title){
      $scope.title = title;
    };
});


<div ng-controller="MyCtrl">
    <h2>{{title}}</h2>
    <button ng-click="setAppTitle('App 2.0')">Upgrade me!</button>
    <div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}">
        <h4>{{title}}</h4>
        <button ng-click="setDirectiveTitle('bob')">Bob it!</button>
    </div>
</div>

However, I've encountered an issue that I would appreciate some clarification on: Why does the <h4>{{title}}</h4> display "Hello World" instead of

"I'm a directive within the app Hello World"
? Can anyone shed light on this for me? Thank you.

Plunker

Answer №1

To ensure isolation, it is necessary to include the template within the directive's template property. Currently, the directive establishes an isolated scope but does not utilize it effectively because the content within the directive tag is already evaluated in the parent scope (MyCtrl) upon triggering the link function.

You may find this example helpful: http://plnkr.co/edit/jmWrNpLFttDPhSooPF0M?p=preview

Directive:

.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        replace: true,
        template: '<div><h4>{{title}}</h4>' +
          '<button ng-click="setDirectiveTitle(\'bob\')">Bob it!</button>',
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };

Markup:

<div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}"></div>

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

How can I integrate the native calendar of an Android device in Phonegap?

What is the best way to add an event to an Android device's calendar using phonegap? I need to make sure it works on Android Version 2.3 and above. The available plugins are not functioning correctly, so I am looking for alternative solutions. ...

problem accessing array values outside of function in JavaScript?

I am facing an issue with my code. I have created an array to store dynamic values from a database. The problem is that when I try to print the array outside of the transaction function, it doesn't display any values even though I have declared the ar ...

The console is still showing an error even though I have updated the record

After updating the existing records in MongoDB, I noticed that the changes are reflected correctly. However, I am still encountering some warnings and errors in the console: {"name":"Bruce","number":"22222","dat ...

Showing the chosen picture in a pop-up window

I developed a user-friendly application using Vue.js that allows users to explore books by selecting author names. I implemented a modal to showcase the books, but encountered an issue where clicking on different cards displayed the same image repeatedly. ...

What methods can be used to save mouse coordinates to a remote server?

As a beginner in server-side programming, I have some questions regarding my project built in JavaScript and Node.js. The current functionality involves sending mouse coordinates to the server and redrawing them on every client's screen. However, new ...

"Submit form data without reloading the page using the $_

I have an associative array that I am using to display images. I want to randomly select two or more pictures from these images with my code, but I have a couple of questions: How can I enhance the efficiency of my code? And is there a way to use JSON or ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...

How to retrieve the value of a variable from one JavaScript function and pass it to another

As a JavaScript beginner, I am looking for help in retrieving values from one function to another. Specifically, I would like to access the values of dinoRight, dinoLeft, and others in the cactus1move function. const spawn = () => { const dinoRigh ...

Difficulty with React Router (slowing down route transition upon clicking) in version 5.2.0

I am facing an issue where, when I click on a link in my navigation bar, the URL lags behind, sometimes requiring me to click twice to get the URL to change successfully. The link path was initially based on state passed through props, which I suspected m ...

How can I resolve the ReferenceError in NextJs which states that Audio is not defined?

Recently, I implemented a Next component that acts as a music player, allowing users to play or stop the audio just like an MP3 player. While the functionality works perfectly fine on my local server – clicking the button triggers the audio play or pause ...

Can passing parameters between nested map functions cause any issues?

While attempting to navigate to a page in reactjs and pass parameters using the useNavigate hook, I encounter an unexpected token error as soon as I include the navigation within the anchor tag. <a onClick={() ={ ...

Is it possible for a three.js material to have different repeat values for a bump map compared to a texture map?

I'm attempting to reduce the repetitive nature of my texture by implementing a bump map that repeats less frequently. However, it appears to adopt the repeat value of 'landTexture' (64) below instead of the value I assigned it (1). landText ...

Can a console application be created using AngularJS technology?

My task involves creating a console application that interacts with an API, modifies the data, and displays it on the console when a specific command is run. Is it feasible to achieve this using AngularJS? If not, what about utilizing Angular6 instead? To ...

Adding more content to the ng-bind-html directive: a guide

There is a unique situation where HTML text can be transformed and displayed within a container div using various filters: <div ng-bind-html="message.message | hrefConvert | rawHtml | test"></div> I am wondering how to incorporate another obj ...

Convert specific form inputs into an array

I have a form that includes various inputs, but the ones I am focusing on are labeled attributes[] and options[$index][]. Here is an example of the data found in my attributes[] input: Array ( [0] => Size [1] => Color [2] => Material ) Not ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Save the processed string into a new array

Will my experimental code function and behave in the same way as my working code, given that the HTML, CSS, and previous JS are functioning properly? If not, what is causing the discrepancy? Additionally, how can I go about creating a loop-array style ver ...

Having trouble displaying Vue Toast messages?

I have been trying to incorporate a toast message into my code, but unfortunately, the message does not appear and there are no errors in the console. The code functions properly and the invitation is sent successfully. I have used similar code in other fi ...

Tips for selecting values from a MongoDB collection using Mongoose

Currently utilizing the MEAN stack, I am attempting to retrieve data from MongoDB using AngularJS. As someone who is fairly new to this technology, I managed to successfully insert values and now need to pull data from MongoDB using Mongoose. Currently ut ...

What is the process for removing specific words from the text?

I am looking for a solution to select words and create an array out of them. Once the words are added to the array, I want to delete them, but I'm unsure of how to do that using either document.getSelection() or document.selection. If anyone has any h ...