Clicking on an option within a div that has an ng-repeat does not update the ng-model

Why is my ngModel, myOpt2, not changing when selected while myOpt does change? Any specific reason for this?

¿Por qué mi ngModel, myOpt2, no cambia al ser seleccionado mientras que myOpt sí lo hace? ¿Hay alguna razón específica para esto?

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

app.controller('Ctrl_Categorias', function ($scope, $http) {

    $scope.lstCatalogos = [{ sNombre: "Vehículos", iID: 1, iIdPadre: 0, bUltimo: false }]
    $scope.lstSubCategorias = []


    $scope.$watch("myOpt", function (newval, oldval) {
        if (newval == undefined || newval.iID == 0) {
            return false;
        }
        $scope.lstSubCategorias[0] = [{ sNombre: "Autos", iID: 17, iIdPadre: 1, bUltimo: true }]
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="example-wrap" ng-app="App_Alta" ng-controller="Ctrl_Categorias" id="AppAngular1">
  <div>
      <header Class="example-title">
          Seleccione una categoria
      </header>
      <div class="example">
          <select class="form-control" 
                  ng-model="myOpt" 
                  selectpicker="{ noneSelectedText: 'Seleccione una opción' }"
                  select-model="lstCatalogos"
                  ng-options="x.sNombre for x in lstCatalogos"></select>
      </div>
      <div class="example" ng-repeat="l in lstSubCategorias">
          <select class="form-control"
                  ng-model="myOpt2" 
                  selectpicker="{ noneSelectedText: 'Seleccione una opción' }"
                  select-model="lstSubCategorias"
                  ng-options="x.sNombre for x in l"></select>
      </div>
  </div>
<p>{{myOpt}}</p>
<p>{{myOpt2}}</p>
</div>

No cambia?

Answer №1

Make sure to verify if myOpt has truly been altered before assigning a new value to myOpt2

$scope.$watch("myOpt", function (newval, oldval) {
  if(newval !== oldval) {
    if (newval == undefined || newval.iID == 0) {
        return false;
    }
    // Assuming this is where the intention is to set myOpt2 based on initial selection
    $scope.myOpt2 = [{ sNombre: "Autos", iID: 17, iIdPadre: 1, bUltimo: true }]
  }
});

Answer №2

If you want to simplify the code, consider utilizing the ng-change directive in place of a watcher:

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

app.controller('Ctrl_Categorias', function ($scope, $http) {

    $scope.lstCatalogos = [{ sNombre: "Vehículos", iID: 1, iIdPadre: 0, bUltimo: false }]
    $scope.lstSubCategorias = [];
    $scope.myOpt2 = [];

    //$scope.$watch("myOpt", function (newval, oldval) {
    $scope.myOptChange = (function(newval) { 
        if (newval == undefined || newval.iID == 0) {
            return false;
        }
        $scope.lstSubCategorias[0] = [{ sNombre: "Autos", iID: 17, iIdPadre: 1, bUltimo: true }]
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="example-wrap" ng-app="App_Alta" ng-controller="Ctrl_Categorias" id="AppAngular1">
  <div>
      <header Class="example-title">
          Seleccione una categoria
      </header>
      <div class="example">
          <!-- USE ng-change directive -->
          <select class="form-control"
                  ng-model="myOpt"
                  ng-change="myOptChange(myOpt)"
                  ng-options="x.sNombre for x in lstCatalogos">
          </select>
      </div>
      <div class="example" ng-repeat="l in lstSubCategorias">
          <select class="form-control"
                  ng-model="myOpt2[$index]"
                  ng-options="x.sNombre for x in l">
          </select>
      </div>
  </div>
<p>{{myOpt}}</p>
<p>{{myOpt2[0]}}</p>
</div>

By using the ng-change directive, you can improve performance as the associated function is only called when there is a change in selection, rather than continuously checking during each digest cycle. This also sets up an easier transition to Angular 2+ since Angular 2+ does not have the $scope.$watch method.

For further details and resources, refer to:

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

Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is no ...

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Generating a JSON download link using AngularJS

I'm attempting to generate a link that will enable the download of a JSON file in this way Controller $scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); View <a href="url" download="download.json">downlo ...

Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case. The browser renders a list of phones. When the user clicks on add phone for one of these phones, the function addItem is triggered and adds that phone ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Can you explain the significance of the syntax "require: ^"?

Can someone explain the significance of the ^ symbol under require in this Angular directive code snippet? I came across this code and am having trouble understanding its meaning. .directive('accordionGroupHeading', function() { return { ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

Angular Material Flex is not providing the correct size

There seems to be a problem with certain values for setting the flex property in the Angular Material layout library. The issue is clearly demonstrated in this straightforward example. By clicking through, you can observe that some values display correctl ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

Which tool would be better for starting a new Angular project: angular-seed or yeoman?

I'm having trouble deciding on the best approach to create a new AngularJS application. There seem to be various methods available, such as using angular-seed from https://github.com/angular/angular-seed or yeoman - http://www.sitepoint.com/kickstar ...

Utilizing the ng-if directive to choose the second element within an iteration of an ng-repeat loop

I am currently working on a project where I need to organize and group content by day. While the grouping function is working fine, I am facing an issue with treating the first two items in the loop differently from the rest. I have experimented with using ...