Updating ngModel value dynamically from controller

I have been trying to update the value of an ngModel variable from my controller, but it doesn't seem to be reflecting in the views. Despite looking at other solutions on SO, nothing has worked for me so far. I am looking for a solution that doesn't involve creating a new directive and have also attempted wrapping the change in $scope.$apply without any luck.

You can see the issue demonstrated in this plunkr.

Below is the code snippet from the plunkr:

JavaScript Controller:

    app.controller('MainCtrl', function($scope) {
  $scope.Attachment = "something"
  $scope.change = function () {
      $scope.$apply(function() {
          $scope.Attachment = "otherthing";
      });
}

HTML:

<body ng-controller="MainCtrl">
    <section class="content" ng-app="offer">
        <div>
            <button name="change" ng-click="change()" ng-model="Attachment">change</button>
            <!-- <input name="Attachment" type="file" class="file_up" onchange="angular.element(this).scope().change(this)" ng-model="Attachment" /> -->
            <span>{{Attachment}}</span>

        </div>
    </section>
</body>

Answer №1

It is recommended to bind to object properties rather than primitive types.
In this case, you are binding to a string which is a primitive type and cannot be changed.
The use of $apply is not necessary as Angular will automatically handle it for you.

If you store your data as a property of an object, you won't lose the reference:

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

app.controller('Ctrl', function($scope) {
  //Updated here:
  $scope.data = {
    Info: "sample"
  }

  $scope.update = function() {
    //Removed $apply from here
    $scope.data.Info = "updated";
  }
});

To reflect this change in the HTML, simply update:

<span>{{data.Info}}</span>

UPDATE: While other responses may be accurate, I wanted to highlight the best practice for binding. Check out the updated demo here.

Answer №2

To enhance the functionality of your code, eliminate the ng-model attribute from the button element and get rid of the $scope.$apply function from the change handler:

http://example.com/sample-code

Answer №3

Feel free to try out this solution

function NewController($scope) {

  $scope.File = "example"
  $scope.modify = function() {

    $scope.File = "different";

  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app ng-controller="NewController">
  <button name="modify" ng-click="modify()" ng-model="File">modify</button>

  <span>{{File}}</span>
</div>

Answer №4

Avoid using $scope.$apply() if possible. I updated the plunkr to automatically update the view without it.

app.controller('MainCtrl', function($scope) {
  $scope.File = "example"
  $scope.update = function () {
      $scope.File = "another";
  }
});

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

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

utilize angularjs to apply the ng-show directive to an input's placeholder icon

Looking to customize the placeholder icon on an ionic-input element, I am using a ng-show directive with two different icons. In my controller, I compare the values of two password fields for equality. If they match, a checkmark icon is displayed; if not, ...

Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image. However, I am facing an issue with the abrupt transition, ...

Sort objects based on a specific property that they possess

In my current setup, I have an array of objects structured as shown below: $scope.people = [{name: {last:"Doe", first:"John"}}, {name: {last:"Smith", first:"Joe"}}]; My goal is to implement a live filt ...

Retrieving form parameters within an EJS template

Hey there! I'm diving into the world of Node.js on my own and hitting a stumbling block that seems simple but is causing me some serious frustration. Despite countless searches on Google, I can't seem to figure it out due to fatigue setting in. I ...

SecretKey is not valid, FirebaseError code: 400

Currently, my backend is powered by Firebase. However, when I initiate it using NODE_ENV=debug firebase emulators:start --inspect-functions, the following messages are displayed: emulators: Starting emulators: auth, functions, storage ⚠ functions: Ru ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Saving the output of mySQL queries on the client side for later use in subsequent requests

While logging a user in, I transfer attributes through a response object. In the javascript, I store specific attributes to a variable for future usage. For example, onresponse - currentUser = req.body.user currentID = req.body.id etc. Later, if I need t ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

Optimal techniques for leveraging CSS within Mui and Reactjs

Just starting out with mui, I'm currently working on styling CSS for mui components like so <Typography variant="h5" sx={{ fontWeight: "bold", color: "#1a759f", display: "flex", ...

Personalized Pop-up Notification Upon Exiting Chrome Tab

I'm trying to implement a custom modal window that appears when the user attempts to close the Chrome Tab where my app is running by clicking the X button, displaying a message asking "Are you sure you want to close?". However, despite my efforts, I a ...

``What is the best way to handle CRUD operations in an Express application?

I have implemented node.js, express, and MongoDB connection with mongoose. Originally, I had a working code in a single file called server.js without using express. However, upon trying to integrate it into express, the functionality is not as expected. T ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

What exactly is the purpose of the script type importmap?

Can you explain the role of <script type="importmap"> and why it has become necessary for my code to function properly? <script type="importmap"> { "imports": { "three": "http ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

Jquery allows for the toggling of multiple checkboxes

I have a group of check-boxes that I would like to toggle their content when checked. Currently, I am using jQuery to achieve this functionality, but I am searching for a way to optimize my code so that I do not need to write a separate function for each ...