Assign the ng-init value of the select-controller in Angular using disabled options

I am encountering an issue with this code:

<div class="year-divider">
    <select style="width:70px;" class="form-control year-selector"
            id="{{'playerYearSelector'}}"
            name="playerCurrYear" data-ng-model="user.playerYears.value"
            data-ng-init="user.playerYears.value = user.playerYears.valueIdx[user.initYearIdx]">
        <option data-ng-repeat="v in user.playerYears.valueIdx"
                value="{{user.playerYears.valueIdx[v]}}"
                data-ng-disabled="user.playerYears.disabled[v]">
           {{user.playerYears.strValues[v]}}
        </option>
    </select>
</div>

In my controller, I have the following setup:

$scope.user = {};
$scope.user.initYearIdx = 3;
var disabled = [ false, false, false, false, false, false, false, false, false, false, true ];
var strValues = [ "-2", "-1", "0", "1", "2", "3", "4", "5", "6", "7", "8" ];
var valueIdx = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
$scope.user.playerYears = {
                                    "value": 3,
                                    "values": values,
                                    "valueIdx": valueIdx,
                                    "strValues": strValues,
                                    "disabled": disabled    };

Despite following what I've read on how to initialize it, the initiation process isn't working as expected. The rest of the functionality works fine, and I can see that the variable ($scope.user.playerYears.value) changes when selecting dropdown options. However, even though the variable is set to an initial value of 3, the controller shows the first element (-2) as selected.

I've attempted calling a function to set the initial value, but that hasn't yielded any results either.

If anyone could provide guidance on resolving this issue, I would greatly appreciate it.

Answer №1

When a field is disabled, using the init function to set its value becomes impossible. The only way to set a value for a disabled field is through module/controller functions. However, it is possible to utilize ng-init on the parent div or in controller div instead. Here's an example:

<div ng-controller="testController as user" ng-init="user.playerYears.value  = user.playerYears.valueIdx[user.initYearIdx]">
  <div class="year-divider">
<select style="width:70px;" class="form-control year-selector"
        id="{{'playerYearSelector'}}"
        name="playerCurrYear" data-ng-model="user.playerYears.value">
    <option data-ng-repeat="v in user.playerYears.valueIdx"
            value="{{user.playerYears.valueIdx[v]}}"
            data-ng-disabled="user.playerYears.disabled[v]">
       {{user.playerYears.strValues[v]}}
    </option>
</select>
</div>
</div>

Answer №2

After researching, it appears that this is the correct way to do it, and the setup is successful.

<select ng-model="selected" ng-init="selected=3"
        ng-options="item.value as item.str
                    disable when item.disabled
                    for item in voirList">
</select>

JS

vm.voirList = [
    {str: "-2", value: 0, disabled: false},
    {str: "-1", value: 1, disabled: false},
    {str: "0", value: 2, disabled: false},
    {str: "1", value: 3, disabled: false},
    {str: "2", value: 4, disabled: false},
    {str: "3", value: 5, disabled: false},
    {str: "4", value: 6, disabled: false},
    {str: "5", value: 7, disabled: false},
    {str: "6", value: 8, disabled: false},
    {str: "7", value: 9, disabled: false},
    {str: "8", value: 10, disabled: true},
    ];

Check out the DEMO on JSFiddle.

If you need more information about the ng-options directive, you can visit AngularJS ng-options API Reference.

Answer №3

If you are working with AngularJs 1.4.0 or a newer version, ngOptions can help you accomplish all your desired tasks.

Here is an example of implementation:

<div ng-app="myApp" 
     ng-controller="MainCtrl">
  <div class="year-divider">
  <!-- showing the binding in action -->
  {{ val }}<br>
    <select style="width:70px;" 
            class="form-control year-selector" 
            id="{{'playerYearSelector'}}" 
            name="playerCurrYear"
            ng-options="val disable when user.playerYears.disabled[val] for val in user.playerYears['valueIdx']"
            ng-model="val">
   </select>
   <span>Two values are disabled</span>
 </div>
</div>

In the controller:

angular.module('myApp', [])
.controller('MainCtrl', function($scope) {

$scope.user = {};
var isDisabled = [ false, false, true, false, false, false, false, false, false, false, true ];
var strValues = [ "-2", "-1", "0", "1", "2", "3", "4", "5", "6", "7", "8" ];
var valueIdx = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
$scope.user.playerYears = {
                        "value": 3,
                        "values": values,
                        "valueIdx": valueIdx,
                        "strValues": strValues,
                        disabled: isDisabled   
                      };
$scope.val = valueIdx[0];
});

Utilize ngModel to set the desired value in the controller instead of using ngInit frequently. Once the user selects an option, the variable will be updated accordingly. Here is the fiddle. The ngOptions directive might seem complex at first glance, but it is ideal for dropdown menus and select tag elements.

Answer №4

If you're encountering issues, there's a solution available. Take a look at the jsfiddle link for guidance. Keep in mind that this fix may not be applicable to angular 1.2 versions.

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope, $filter) {
    $scope.user = {};
    var disabled = [false, false, false, false, false, false, false, false, false, false, true];
    var strValues = ["-2", "-1", "0", "1", "2", "3", "4", "5", "6", "7", "8"];
    var valueIdx = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    var values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    $scope.user.playerYears = {
      "value": "3",
      "values": values,
      "valueIdx": valueIdx,
      "strValues": strValues,
      "disabled": disabled
    };
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
    <div class="year-divider">
      <select style="width:70px;" class="form-control year-selector" id="{{'playerYearSelector'}}" name="playerCurrYear" data-ng-model="user.playerYears.value">
        <option data-ng-repeat="v in user.playerYears.valueIdx" value="{{user.playerYears.valueIdx[v]}}" data-ng-disabled="user.playerYears.disabled[v]">
          {{user.playerYears.strValues[v]}}
        </option>
      </select>
    </div>
  </div>
</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

The StrongLoop ng-lb command encounters issues when utilizing the local-storage-connector

Hello Strongloop community, I have been experimenting with the local-storage data store example provided by loopback. It's working well and I can successfully create and retrieve files from the local file system (used as a data source) using the REST ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

Guide on implementing a live media stream using JavaScript

I am looking to set up a live audio stream from one device to a node server, which can then distribute that live feed to multiple front ends. After thorough research, I have hit a roadblock and hope someone out there can provide guidance. I have successf ...

Encountering an unexplained JSON error while working with JavaScript

I'm trying to retrieve data from a JSON API server using JavaScript AJAX and display it in an HTML table. However, I keep encountering an undefined error with the data displaying like this: Name id undefined undefined This is my code snippe ...

Display content in the View in ASP.NET based on the parameters passed into the ActionResult function

I'm grappling with a theoretical scenario involving rendering a single View with different content based on user input using MVC in the .NET framework. Essentially, I'm looking to have just one page titled "Create Template", but its contents sho ...

Arrange elements based on the selected dropdown menu

I'm currently utilizing Twitter Bootstrap 2.3.2 along with the chosen plugin for select boxes. I have a question regarding how to align other elements based on the box with selected items. Below, you can see two select boxes and content (elements) po ...

The Angular application's Protractor end-to-end test works flawlessly on a local machine but encounters issues when executed in the Azure DevOps

I am facing a challenge while running end-to-end tests on my Angular application. The tests pass successfully locally when I run ng e2e, but they fail in the pipeline environment. Below, I will provide details of my protractor.conf file, the tasks in the p ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

Observing the transformation that occurred within the operation thanks to the guidance of the

How can I effectively listen to changes in my injected service within the controller? In the code example below, there are two instances of using $watch - one that works but is unclear why, and another that seems intuitive but fails. Is the second approach ...

Toggle table column visibility in AngularJS by using a dropdown selection in the first column

Implementing angularjs I have a situation where I have a table with two columns. The first column is linked to an array, while the second column contains a dropdown menu. My goal is to display or hide 5-6 additional columns (containing text and dropdowns ...

Command for Pinging in Discord.js

I attempted to create a ping command for my bot, and here is the code I used: client.on('message', message => { if (message.content === '+ping') { message.channel.send(` ...

Getting the updated state value instantly within the useEffect hook

I've been facing an issue where I update the value of a state and then attempt to use it inside useEffect, but I am unable to access the updated state. Can anyone provide guidance on how to retrieve the updated state immediately within useEffect? Tha ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

Obtain the cookie and store it in a variable (with a 24-hour expiration) before transferring it to

I am in need of a unique variable that is valid for a single day. This variable should be able to identify the individual website user and remain exclusive to that user. Once obtained, I intend to store this variable in a MySQL column. However, I am facing ...

Managing ajax requests, failing to retrieve information

I am struggling to configure my client-side ajax calls to send data to a node express server. I want the ajax request to be triggered "onclick" of an href link. My goal is to pass the ID of the link as a variable to the server, but unfortunately, the serv ...

Using Vue.js to link and update dynamic form fields

I have developed a dynamic set of form inputs utilizing vue.js, where the form inputs are generated from an external list of inputs. My challenge lies in figuring out how to bind the input values back to the vue model, enabling the vue instance to access ...

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

Concerns arise with jQuery grid compatibility in Firefox browsers

I have found an interesting tutorial on draggable image boxes grid at this link. Although everything is functioning properly, I am encountering an issue with the drag function specifically on the home page when using Firefox. As a beginner in jQuery, I am ...

The Bookshelf JavaScript model is creating a never-ending cycle of saving and changing data

In the Bookshelf model provided below, the users password is hashed when the model is saved. However, an issue arises when changing the model.set() call to a model.save(), leading to an endless loop of saving and changing. var User = bookshelf.Model.ext ...