Exploring the passing of parameters in Angular JS getters

In my Angular 1.6.x project, I have a collection of checkboxes that store their state in a variable called selectedJobIds. This variable contains the ids of selected jobs along with their corresponding true or false values:

$scope.selectedJobIds = {
 23: true,
 56: true,
 47: false
}

My goal is to check the checkboxes for those ids that exist in this object and have a value of true. Additionally, checkboxes should be checked even if they are not present in the object.

The current issue is that the program cannot distinguish between non-existent ids and ids with a false value. As a result, it unchecks both types.

Here are the approaches I've attempted:

  1. I tried implementing a ternary condition in the ng-model attribute:
    ng-model="(angular.isDefined(selectedJobIds[job.iid])?selectedJobIds[job.iid]:true)"
    However, this resulted in a syntax error.
  2. I also experimented with using getter/setter functions in ng-model-options. The challenge here was passing the job id to the getter function and accessing the scope of the current element to determine its existence in the selectedJobIds variable.

HTML:

<ul class="list-unstyled filtered-trucks-ul">
  <li ng-repeat="job in dType track by $index" style="vertical-align: middle;">
      <input type="checkbox" name="job_id" value="{{job.iid}}"
             ng-click="selectFilterJob()"
             ng-model="selectedJobIds[job.iid]" />
      <img src="23.png">
      {{ job.rref + ' (' +job.iid+ ')' | uppercase }}
      </li>
</ul>

JS:

$scope.checkedFilteredJobs = {
    getterFunc: function(newName) {
        console.log(newName)
        // if(angular.isDefined($scope.selectedJobIds[id]))
        // {
        //    return $scope.selectedJobIds[id];
        // }
        // else {
        return true;
        // }
    }
};

Answer №1

To cover missing properties, utilize ng-init:

var app = angular.module('myApp', []);

app.controller('myAppController', ['$scope', function($scope) {

  $scope.dType = [{iid: 23}, {iid: 56}, {iid: 47}, {iid: 1234}, {iid: 888}];
  $scope.selectedJobs = {
    23: true,
    56: true,
    47: false
  };

  $scope.initMissing = function(job) {
    if (!$scope.selectedJobs.hasOwnProperty(job.iid))
      $scope.selectedJobs[job.iid] = true
  }

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="myApp" ng-controller="myAppController">
  <ul>
    <li ng-repeat="job in dType track by $index">
      <input type="checkbox" ng-init="initMissing(job)" name="job_id"
             ng-model="selectedJobs[job.iid]" />
    </li>
  </ul>
</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

What is the best way to update a specific element within a web page?

My current implementation involves utilizing this code snippet within a functional component : return ( <div style={{ height: "700px", overflow: "auto" }}> <InfiniteScroll pageStart={0} loadMore={Fet ...

Error: The post request was blocked due to cross-origin restrictions

This is my unique script /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ var app=angular.module('todoApp ...

Having trouble retrieving a JavaScript Object from a promise in Node.js

I am attempting to retrieve a JSON report with two parts and convert it into a JavaScript object in my mainFile.js, as demonstrated below: file1.js module.exports = async (param1, param2) => { try { await fun1(param1, param2); await ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Vue.js - experiencing issues with conditional styling not functioning as expected

Can someone help me with an issue I'm having? I've created a button with a heart symbol that is supposed to change color when clicked, but it's not working as expected. This is my current code: <template> <button v-bind: ...

Uploading Files Larger than 5MB on AWS Using Node.js

I have been utilizing this module to upload files to Amazon. The module can be found at https://www.npmjs.com/package/streaming-s3 and it works perfectly for files that are 5 MB or less. However, when I attempted to upload a PDF file that was 6 MB in size ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

What is the most effective method for exchanging data between a server and an Angular client?

We've been working on a web application that uses both C# and Angular for development. Communication between the client and server is done through JSON to exchange data. One issue I've encountered as a frontend developer is that when the model& ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

What are some recommended security measures for JSON data?

During my exploration of the topic of JSON vs XML, I stumbled upon this particular question. One of the arguments in favor of JSON was its ease of conversion in Javascript, specifically using the eval() function. However, this raised some security concerns ...

What is the best way to position a popup div in CSS?

Currently, I am in the process of developing a website that displays DVD details when hovering over an image, similar to what is shown in picture 1. However, I've encountered an issue where the content gets cut off for DVDs located on the right side o ...

Angular's handling of cached data returned from HTTP requests experiencing issues

In my controller, I have the following code snippet: var cache = $cacheFactory('contacts'); var data = cache.get('contacts'); if(!data) { Contacts.get() .success(function(result) { data = result; c ...

What is the best way to access a post request value from one JavaScript file to another in a Node.js environment

Hey there, longtime listener, first-time caller. I'm diving into the world of node JS, Javascript, and express but I've hit a roadblock that's been giving me a headache for three days now. Hoping someone here can lend a hand. I have a &apos ...

What are the steps to bring in a module from a URL?

I have integrated a Vue.js npm package into my application. However, due to certain reasons, I now need to directly use the CDN URL. Let's assume that this is the CDN link for the library: https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-prot ...

Apache2 is displaying a 403 Forbidden Error

Working on setting up Apache2 on my Ubuntu system has been a successful endeavor. However, I am encountering a challenge in configuring a server for my AngularJS project's HTML pages. Currently, the directory is as follows: <Directory /var/www/htm ...

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

What is the best way to show two icons next to each other within a React component?

For my school project, I am working on developing an app and encountering a challenge. I have been trying to display two icons side by side on a screen using React (I've been learning React for 5 months but still consider myself a beginner). However, ...

Tips for navigating the world of hybrid web applications that combine elements of both traditional multi-page applications and single-page

What are some best practices for developing a multi-page application using modern JavaScript frameworks? Multi-page Application In a multi-page application, we utilize multiple templates with "template syntax" to retrieve backend data and handle AJAX (if ...