HTML not being displayed in AngularJS Directive template

Check out my fiddle here, where I am trying to build a group of checkboxes. Everything works perfectly in the prototype, allowing me to include multiple groups that run independently. However, when I added the code to my app and inserted the html template: '<>', the directive does not display. The model data inside the handle bars in the template is visible though. I can't seem to figure out what the issue is as there are no errors.

You can also view this working example on Plunker here

<div class="sqs" >
        <pre>
            {{survey | json}}
        </pre>

        <suvey-checkbox ng-model="Q1" ng-init="surveyQuestions = [
                { 'value':'value1', 'name': 'The unit' }, 
                { 'value': 'value2', 'name': 'Patient Threw Up'}, 
                { 'value':'value3', 'name': 'Unsafe for children' }, 
                { 'value':'value4', 'name': 'Actively dying, reached life goal'}]">
        </suvey-checkbox>

        <suvey-checkbox ng-model="Q2" ng-init="surveyQuestions = [
                { 'value':'value1', 'name': 'The unit' }, 
                { 'value': 'value2', 'name': 'Patient Threw Up'}, 
                { 'value':'value3', 'name': 'Unsafe for children' }, 
                { 'value':'value4', 'name': 'Actively dying, reached life goal'}]">
        </suvey-checkbox>
</div>

Meanwhile

var app = angular.module("app", []);
app.run(function($rootScope){
$rootScope.survey = [];
});

app.directive('suveyCheckbox', function ($rootScope) {
return {
    restrict: 'E',
    require: '^ngModel',
    scope: {
        ngModel: '@'
    },
    template: '{{ngModel}}<br /><label ng-repeat="surveyQuestion in      surveyQuestions" class="checkbox">' +
                '<input data-role="none" type="checkbox" name="selectedExclusion[]" value="{{surveyQuestion.value}}"' + 
                'ng-checked="surveyAnswers.indexOf(surveyQuestion.value) > -1" ng-click="togglesurveyAnswers(surveyQuestion.value)"> ' +
                '{{surveyQuestion.name}} <br /></label>{{surveyAnswers}}',
    link: function (scope, elem, attr) {
        // selected exclusion
        scope.surveyAnswers = [];

        // toggle surveyAnswers for a given answer by name
        scope.togglesurveyAnswers = function togglesurveyAnswers(surveyQuestion) {
            var idx = scope.surveyAnswers.indexOf(surveyQuestion);

            // is currently selected
            if (idx > -1) {
                scope.surveyAnswers.splice(idx, 1);
            }
            // is newly selected
                else {
                scope.surveyAnswers.push(surveyQuestion);
            }
        };
        $rootScope.survey.push(scope.surveyAnswers);
    }
}
});

The code from the linked fiddle prototype doesn't seem to work for some reason.

Answer №1

In newer versions of Angular, the code may not function as expected. This is due to a bug in previous versions where isolate scopes were not truly isolated and could leak out to other directives.

However, in Angular 1.2.x, isolate scope is genuinely isolated. This means that any variables used in the template must either be manually added to the scope by the directive or included in the isolate scope definition (e.g., scope: { myVar: '='}).

For instance, if your template needs to access surveyQuestions, it must be defined in the isolate scope. Otherwise, functions like ng-init will not have access to the isolate scope within the surveyCheckbox directive.

To enable the use of surveyQuestions in your directive's template, you need to pass it into the isolate scope:

<survey-checkbox questions="surveyQuestions" ng-model="bedsideQ2" ng-init="surveyQuestions = [
     { 'value':'value1', 'name': 'The unit' }, 
     { 'value': 'value2', 'name': 'Patient Threw Up'}, 
     { 'value':'value3', 'name': 'Unsafe for children' }, 
     { 'value':'value4', 'name': 'Actively dying, reached life goal'}]">
</survey-checkbox>

Then, include it in your isolate scope:

scope: {
   ngModel: '@',
   surveyQuestions: '=questions'
}

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

Ways to include additional assurances depending on a specific circumstance

When my code is executed in edit mode, I have a selection of API calls that need to be made, as well as one specific API call that must be made in both create and edit modes. Here is the current code snippet: // other controller code var config = {}; ...

Improved AJAX Dependency

A few days ago, a question was posted with messy code and other issues due to my lack of experience (please forgive the form handling as well). However, I have made some improvements and added context. The main problem now lies in the second AJAX call. Ch ...

Adjusting the size of SVG elements using AngularJS

As someone just starting out with AngularJS, I'm currently working on a project involving SVG elements that have fixed width and height. Unfortunately, this is causing issues when it comes to creating a responsive graph application. Can anyone provide ...

Is there a way to integrate AngularJS with XAMPP for server communication without utilizing Node.js?

I've been using XAMPP for my programming web applications, primarily with PHP. However, I've now made the switch to AngularJS. The problem is, I can't seem to find any tutorials on server communication without Node.js Since I'm not co ...

Activate numerous progress bars to animate as the user scrolls beyond the designated anchor point

Check out my website here: I've spent a lot of time working on this site, but I've hit a roadblock when it comes to animating the skill bars. I still want them to animate as users scroll past a certain point, but I'm struggling to figure it ...

Utilizing a dynamically created Stripe checkout button

Currently, I am attempting to integrate a checkout button from the Stripe Dashboard into my VueJS Project. I have a feeling that I might not be approaching this in the correct manner, so if you have any advice, I would greatly appreciate it. In order to ...

The equation:() is malfunctioning

Here is a code snippet I'm working with: $("#button").click(function () { for (var i = 0; i < 4; i++) { setTimeout(function () { $(".rows:eq("+i+")").css("background-color", "blue"); ...

Personalizing buttons on a carousel in React-bootstrap

I am facing an issue with my carousel and buttons placement. The buttons need to be outside of the carousel, but I'm unsure how to connect them effectively. React-Bootstrap's activeIndex option was suggested, but since my carousel is not cyclic l ...

Nodemon has encountered an issue: Unable to listen on port 5000. The address is already in use

During the creation of my project with nodejs and express for the backend, everything was running smoothly. However, whenever I made changes to a file, nodemon would encounter an error preventing the server from restarting: Error: listen EADDRINUSE: addre ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

What causes AsyncStorage to lose one value while another value remains intact?

My last session id is stored using AsyncStorage, but for some reason it loses a specific value and I can't figure out why. I created an app that should automatically select the last chosen group on startup. However, after restarting the app, AsyncSto ...

Retrieve the live value for plugin settings following the completion of DOM loading. (Fineuploader plugin)

I am seeking assistance with a situation. I am utilizing Fineuploader and I need to access and transmit the value of an input field (which will serve as the file group title). To achieve this, I am using the path to a server-side script (as I did not wri ...

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

Start the setInterval function again after clearing it with the clearInterval button, but wait for

Currently, I am working on a content slider that automatically cycles through slides using the "next" function and setInterval. However, I want it to stop when the user clicks on the prev/next buttons by using clearInterval. Is there a way to resume setInt ...

What benefits does the functional syntax of setState offer when used in React functional components?

Let's discuss functional components with the useState hook. For example: const [age, setAge] = useState(0) Now, when updating the age, we may need to use its previous value. This is where FUNCTIONAL UPDATES come in handy. You can pass a function th ...

Monitoring changes in an array of objects using AngularJS's $watch function

Exploring the world of AngularJS, I'm on a quest to solve a challenging issue efficiently. Imagine having an array of objects like this: var list = [ {listprice: 100, salesprice:100, discount:0}, {listprice: 200, salesprice:200, discount:0}, {listpr ...

What steps should be taken to address the Chrome alert stating that the deferred DOM Node cannot be identified as a valid node?

While working on my node.js project hosted on a localhost server, I've encountered an unusual warning message in the inspector. The warning states: The deferred DOM Node could not be resolved to a valid node. Typically, I use the inspector to examine ...

Confirmed the validation of an input that falls outside the parameters of the ReactiveForms model

Check out this StackBlitz example In my Angular application, I am utilizing a Reactive form with 3 inputs, each having its own validation. Additionally, there is an input that exists outside of the form within its own component, also with its own reactive ...

What makes Nuxt/auth so highly secure?

Picture this scenario: a visitor lands on your Nuxt.js website's homepage. They proceed to authenticate themselves using @nuxtjs/auth-next. After successfully logging in, they gain access to a protected page meant exclusively for authenticated users. ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...