The AngularJS ngModel directive encounters issues when used within a ui-bootstrap tabset

Check out the code snippet below to see the issue at hand:

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script src="https://code.angularjs.org/1.3.6/angular.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
    <script>
angular.module('plunker', ['ui.bootstrap'])
.controller('MainCtrl', function($scope) {
  $scope.changes = 0;
  $scope.updateValueInScope = function () {
    $scope.valueInScope = $scope.value;
    $scope.changes++;
  }
});
    </script>
  </head>

  <body ng-controller="MainCtrl">
    <tabset>
      <tab heading="Tab A">
        <div class="panel">
          <input type="text" ng-model="value" ng-change="updateValueInScope()" />
          <br />
          <tt>value: {{value}}</tt><br />
          <tt>valueInScope: {{valueInScope}}</tt><br />
          <tt>changes: {{changes}}</tt>
        </div>
      </tab>
    </tabset>
    <input type="text" ng-model="value" ng-change="updateValueInScope()" />
    <br />
    <tt>value: {{value}}</tt><br />
    <tt>valueInScope: {{valueInScope}}</tt><br />
    <tt>changes: {{changes}}</tt>
  </body>

</html>

Try it out on Plunker:

http://plnkr.co/edit/dJc009csXVHc7PLSyCf4?p=preview

This piece of code features two textboxes, one within a tabset and one outside. Both are connected to the value scope variable. Interestingly, changing the content of the textbox inside the tabset does not update the value variable in the scope, while modifying the textbox outside the tabset does. Any changes made to either textbox will trigger a call to updateValueInScope() through ngChange.

I am intrigued by this behavior and would appreciate an explanation as to why it occurs. Is there a way to resolve it so that the textbox inside the tabset can effectively modify the model in the scope?

Answer №1

It's highly likely that the problem arises from attempting to bind to a primitive data type (specifically a float). You can resolve this issue by making changes like the following:

$scope.data = {}
$scope.updateValueInScope = function () {
  $scope.data.valueInScope = $scope.data.value;
  $scope.changes++;
}

In Angular, when you bind to a primitive, the value itself is passed rather than its reference. This can cause problems with 2-way binding. It seems that the tabset directive creates its own scope, causing the valueInScope variable in the controller to lose its binding in the child scope of the tabset due to it being a primitive. Avoid binding to primitives to resolve this issue.

For a corrected version, check out this updated plunk example.

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

When I attempt to run JavaScript code on the server, it fails to execute properly

When I run my code on my PC without putting it on the server, it works perfectly fine. However, when I upload it to the server and try to call it, I encounter the following error: Uncaught ReferenceError: crearLienzo is not defined at onload ((index): ...

Incorrect pagination handling using AngularJS bootstrap

HTML Code <body ng-app="MyApp"> <div ng-controller="PaginationCtrl"> <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th& ...

Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this: { & ...

Navigating through arrays in JavaScript - optimizing performance

I've noticed this code snippet used in various places: for (var i = 0, len = myArray.length; i < len; i++) { } I understand that this is caching the length of the array. Recently, I encountered this alternative approach: var len = myArray.le ...

When attempting to call Firebase Functions, ensure that Access-Control-Allow-Origin is set up correctly

Although it may seem straightforward, I am confused about how Firebase's functions are supposed to work. Is the main purpose of Firebase functions to enable me to execute functions on the server-side by making calls from client-side code? Whenever I t ...

Utilize JSON parsing to extract and store data into an object

I'm currently working on extracting specific objects from a parsed JSON stored within an object named data.json. var data = { json: '', text: '', welcome: '', q1: '', } let foo = await fetch(spr ...

Issue with Bootstrap contact form functionality in PHP not working

I have experience in coding HTML and PHP, but unfortunately, [email protected] (mail address) is still unable to receive emails from my website (http://cloudsblack.info/) and when I click the submit button, it leads to a blank page (http://cloudsblack.info ...

Using ng-if to compare dates in AngularJS without considering the year

I am facing a comparison issue with dates in my code. I have one date that is hardcoded as the first day of the month, and another date coming from the database (stored in a JSON object). When I compare these dates using ng-if, it seems to ignore the year ...

Dynamic file name and title for jQuery Datatables Export Buttons

I am utilizing jQuery datatable along with Export buttons. When adjusting the filename and title, I encounter an issue. The problem lies in my desire for the title to be dynamic, depending on the applied filters and custom ones. Additionally, configurin ...

Retrieving output from a JavaScript function

When running the code, the following logs are generated: "generating my graph" myMain.js:110 "Getting credits" myMain.js:149 "debits array is 3.9,4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8" myMain.js:169 "Credits data = 10.7,20.5" myMain.js:156 ...

What could be causing the absence of several nodes in my three.js animations?

As I work on creating a portfolio using three.js, I've encountered an issue with my animation sets not playing after triggering an event. Initially, the code worked fine, but now I keep receiving a series of warnings and the code doesn't run at a ...

The feature for favoriting or unfavorite a post is currently not functioning correctly on the frontend (react) side

I have been working on a social media website project for practice, and I successfully implemented the liking and disliking posts feature. However, I encountered an issue where when I like a post and the icon changes to a filled icon, upon refreshing the p ...

Interested in retrieving the dynamically changing value of LocalStorage

Hopefully I can articulate my issue clearly. I am implementing a feature where CSS themes change upon button clicks. When a specific theme button is clicked, the corresponding classname is saved to LocalStorage. However, since the key and value in LocalSt ...

My app is having trouble updating routes correctly. Can anyone provide guidance on how to configure routeConfig properly for my application?

I'm facing an issue with my angular 2 typescript app component routes not working properly. Whenever I try to change the route to login in the address bar, it fails to load the corresponding HTML content. Strangely, there are no console errors displa ...

Make sure that JSON.stringify is set to automatically encode the forward slash character as `/`

In my current project, I am developing a service using nodejs to replace an old system written in .NET. This new service exposes a JSON API, and one of the API calls returns a date. In the Microsoft date format for JSON, the timestamp is represented as 159 ...

What is the method for retrieving a temporary collection in a callback function when using node-mongodb-native find()?

Is it possible to retrieve a temporary collection from a find() operation instead of just a cursor in node-mongodb-native? I need to perform a mapReduce function on the results of the find() query, like this: client.open(function(err) { client.collect ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

Achieving the functionality of toggling a div's visibility using jQuery by simply clicking on a

Here is the JavaScript code I am using: $(document).ready(function() { $('.LoginContainer').hide(); $('.list li a').click(function(){ $('.LoginContainer').togg ...

Why is it that when a boolean value is logged as a checkbox, it shows up as undefined?

In my code, I'm attempting to log the value of a variable named check, which corresponds to column 11 in a spreadsheet. This variable is meant to represent the state of a checkbox (true or false) based on whether it's been ticked or not. However, ...