Issues with ng-model disappearing while using ng-include (AngularJS)

Currently working on an Android app with Ionic and AngularJS. Using ng-include to include HTML content in the app's pages.

checkbox.html:

<ul>
        <li ng-repeat="opt in $parent.checkboxOptions">
            <h4>
                <label><input type="checkbox" name="checkbox" ng-model="$parent.checkboxAnswer" value="{{opt.option_value}}">{{opt.option_value}}</label>
            </h4>
        </li>

</ul>

surveyCtrl.js

$scope.checkboxOptions = params.QuestAnswers;
$scope.next = function(){
    console.log($scope.checkboxAnswer);
}

The issue is that it shows undefined, and when clicking on one checkbox, it selects all checkboxes as well.

https://i.stack.imgur.com/sGaif.jpg

surveyCtrls.js

 .directive('question', function ($compile) {
    return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.question, function(QuesHtml) {
        ele.html(QuesHtml);
        $compile(ele.contents())(scope);
       });
    }
  };
  })

 .directive('description', function ($compile) {
     return {
      restrict: 'A',
      replace: true,
      link: function (scope, ele, attrs) {
        scope.$watch(attrs.description, function(DescHtml) {
          ele.html(DescHtml);
          $compile(ele.contents())(scope);
          });
      }
    };
  })

 .directive('answers', function ($compile) {
    return {
    restrict: 'A',
     replace: true,
      link: function (scope, ele, attrs) {
       scope.$watch(attrs.answers, function(AnswerHtml) {
        ele.html(AnswerHtml);
       $compile(ele.contents())(scope);
     });
   }
  };
 })
.controller('surveyLoad', function($scope){


var QuestType  =  SurveyData[QuestionIndex].question_type;

var DrawHTML = {
                  'QuestionText': 'Some Text', 
                  'QuestionDesc': 'Some Desc',
                  'QuestAnswers': [{
                                      option_value: 'Red',
                                   }, {
                                      option_value: 'Blue',
                                   }];,
                  'scope'       : $scope
               };

  checkbox(DrawHTML);

}

})


 .controller('nextQuest', function($scope){

    $scope.QuestNext = function(){
       console.log($scope);
    }

 });


function checkbox(params){

   var $scope = params.scope;
   $scope.QuesHtml = "<p>"+params.QuestionText+"</p>";
   $scope.DescHtml = "<p>"+params.QuestionDesc+"</p>";

   $scope.checkboxOptions = params.QuestAnswers;
   $scope.AnswerHtml = "<div ng-include src=\"'surveyTemplate/checkbox.html'\"></div>";
}

survey.html

<div class="row">
            <div class="col question_div">
                <div class="qus_head">
                    <p>Question:  1/10</p>
                </div>
                    <h4 class="para"><span question="QuesHtml"></span> </h4>
                <div class="qus_footer">
                    <p>Maxime quis.</p>
                </div>
            </div>
        </div>


        <div answers="AnswerHtml">

        </div>



        <div class="row">
            <div class="col button_div">
                <ul>
                    <li><a href=""><img src="../img/next.png" style="width:70px;float:right" alt="next" ng-controller="nextQuest" ng-click="QuestNext()"></a></li>
                    <!-- <center><li><button style="align:center">Stop</button></li></center> -->
                    <li><a href=""><img src="../img/pre.png" style="width:70px;float:left" alt="previous" ></a></li>
                </ul>
            </div>
        </div>

Seeking a solution to obtain the values of checked checkboxes and prevent others from being checked simultaneously.

Answer №1

When using ng-includes, it creates its own scope. To overcome this issue, utilize the controller as syntax. https://docs.angularjs.org/api/ng/directive/ngController

<div id="ctrl-as-exmpl" ng-controller="Controller as ctrl">
   ...
    <li ng-repeat="opt in ctrl.checkboxOptions">
        <h4>
            <label><input type="checkbox" name="checkbox" ng-model="ctrl.checkboxAnswer" value="{{opt.option_value}}">{{opt.option_value}}</label>
        </h4>
    </li>
   ...
</div>

In your controller:

$scope.checkboxOptions = params.QuestAnswers;

can be rewritten as:

this.checkboxOptions = params.QuestAnswers;

See an AngularJS plunker demonstrating this syntax here: https://plnkr.co/edit/DB1CpoWLUxQ9U8y558m1?p=preview

Best regards, Eric

Answer №2

It appears that there are some errors in the html code that need to be corrected.

<label><input type="checkbox" name="checkbox" ng-model="opt.option_value">{{opt.option_value}}</label>

By using

ng-model="$parent.checkboxAnswer"
, all checkboxes will share a common model.

This means that when you update one checkbox, it will reflect on all of them simultaneously.

Therefore, when you toggle the checkbox, it will affect all checkboxes at once.

Additionally, there is no need to use the value attribute as Angular uses the ng-model property for value evaluation instead.

Answer №3

Woohoo! I've cracked the code...

Check out the solution below:

<ul>
        <label ng-repeat="option in $parent.checkboxOptions">
            <li>
                <h4>
                    <label><input type="checkbox" name="checkbox" ng-model="$parent.$parent.selected[option.option_value]">{{option.option_value}}</label>
                </h4>
            </li>
        </label>
    </ul>

Answer №4

(function(angular) {
  'use strict';
  angular.module('MyApp', [])
    .controller('AppCtrl', SettingsController1);

  function SettingsController1($scope) {

    $scope.options = {
      'checkboxAnswer': ''
    };
    $scope.checkboxOptions= [{
      type: 'phone',
      value: '917xxxxxxxx'
    }, {
      type: 'email',
      value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b6a4afa4abaeb0a8a4b7b385a0bda4a8b5a9a0ebaab7a2">[email protected]</a>'
    }];
  }


})(window.angular);

radio box template file #radiobox.html

<ul>
  <li ng-repeat="opt in checkboxOptions">
    <h4>
            <label><input type="checkbox" ng-model="options.checkboxAnswer" ng-true-value="'{{opt.value}}'" ng-false-value="''">{{opt.type}}</label>
        </h4>
  </li>

  <h1>{{options.checkboxAnswer}}</h1>

</ul>

//in main index.html you can simply add the radiobox.html using the ng-include directive

 <body ng-app="MyApp">
  <div ng-controller="AppCtrl">
      <div ng-include='"radiobox.html"'></div>
  </div>

</body>

If you're not in an isolate scope, there is no need to use $parent in this case. I have created a simple demo for better understanding. Please check the following link: https://plnkr.co/edit/aQMZBln5t0Fipwn1qloN?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

ion-grid featuring alternate columns

As someone who is not very familiar with Angular, I am trying to create a grid layout like the one shown here: https://i.stack.imgur.com/nBavk.png The desired layout includes alternating rows with one image followed by two images. My current attempt at a ...

Ensuring a Proper Shutdown of Adobe's Creative Cloud Web SDK

We have successfully developed a single page application by integrating the Creative Cloud Web SDK with AngularJS. Currently, we are encountering an issue where references to the editor's elements continue to exist on the page even after the editor is ...

Executing Angular directive when ng-change event occurs

I'm encountering an issue with my angular-bootstrap modal popup box that includes a custom directive in the template: Modal.html <div class="modal-header"> <h3 class="modal-title">Modal Header</h3> </div> <div class="m ...

Custom directive to change the background image is not functioning as expected

HTML: <div class="has-bg" back-img="{{currentCoverImg}}" style="min-height: 1000px"> ...... </div> I came across a post discussing the correct method of binding data to a directive and using it in my code. The backImg directive is ...

Encountering issue: LineChart is not recognized as a constructor, resulting in failure to display chart on webpage

I am struggling with displaying a chart in my HTML file that should show the details of a specific process from the past few minutes. Whenever I try to initialize the chart using google.charts.load('current', {'packages':['line&apo ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

What sets apart AngularJs's complete $http post from its shorthand counterpart $http.post?

When sending Object data from app.js to homecontroller using two different methods (full $http.post and shorthand $http.post) as shown below: var book = { "title" : $scope.addTitle, "publisher" : $scope.publisherSelected[0], "authors" : $scope ...

Angular's $cookies are limited to functioning solely on the 'localhost' domain

Prepare yourself, an unusual Angular / IIS issue is on the horizon: I have developed an Angular 1.4.0 application that utilizes $cookies to store the oauth access token once a user logs in. Everything runs smoothly on localhost but encounters issues when ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...

What could be causing the HelloWorld program in AngularJS to malfunction?

To access the codes, you can visit http://jsfiddle.net/hh1mye5b/1/ Alternatively, you can refer to: <!doctype html> <html ng-app="dcApp"> <head> </head> <body> <div> <div ng-controller="SpeciesController"> ...

Custom sparkline array

In working on my sparkline chart, I have the following code snippet: <div sparkline="" values="4,4,7,5,9,6,4" data-type="line" data-height="80" data-width="100%" data-line-width="2" data-line-color="#dddddd" data-spot-color="#bbbbbb" data-fill-c ...

Issue encountered while logging into mobile application built with Ionic 3, Angular 4, and Firebase: Error message received - Unable to sign in using provided email. Email must be a valid string

I am currently working on developing a chat application using Firebase. The user registration process in Firebase is functioning properly. However, I encounter an error message when attempting to log in with a registered username (email address): Error: R ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Using AngularJS to connect a REST search endpoint to $resource mapping

The ng-resource module in AngularJS provides a default set of resource actions which include 'get', 'save', 'query', 'remove', and 'delete'. { 'get': {method:'GET'}, ...

Monitoring separate upload progress within $q.all() in AngularJS

I recently started using the angular-file-upload module created by danialfarid (https://github.com/danialfarid/angular-file-upload) and I must say, it's been a great experience so far. After successfully integrating it into my wrapper service for RES ...

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

AngularJS ng-model not refreshing its data

I am currently facing an issue with my HTML code. The problem is that the model (filter) changes when I select one of the static options, but it does not trigger a change for the dynamic options. Any suggestions on how to fix this? Thank you. <div cla ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

Using AngularJS promises within a loop

I have been working on a code snippet that iterates through the list of reports, modifies each one's name, and performs an update operation. Everything seemed to be in order when there was only one report in the list. However, things went haywire when ...