Controller unable to update AngularJS view

As the title suggests... I'm facing a challenge with this code snippet:

(function(angular) {
  'use strict';
  angular.module('app', [])
    .controller('ctrl', ['$scope', function($scope) {
      $scope.init = function() {
        $scope.response = "press the button";
      }();

      $scope.data = {
        availableOptions: [{
          id: '1',
          name: 'num'
        }],
        selectedOption: {
          name: 'selected field'
        }
      };

      $scope.data2 = {
        availableOptions2: [{
            id: '0',
            name: 'null'
          }
        ],
        selectedOption2: {
          name: 'null'
        }
      };

      $scope.search = function() {
        $scope.response = "you pressed a button \\o/";
        alert($scope.response);
      };

      $scope.request = function(req) {
        $http(req).then(function() { /*successCallback*/ },
          function() { /*errorCallback*/ });
      };

    }]);
})(window.angular);
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="//code.angularjs.org/1.7.3/angular.min.js"></script>
  <script src="analyzer.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="ctrl" ng-show="true">
    <!--class="ng-hide" is automatically added when ng-show="false"-->

    <!--SEARCH-->
    <form name="myForm">
      <label for="mySelect">Select a field:</label>
      <select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>
      <br/>
      <div style="color:#757575">
        <input ng-model="query" type="text" size=45 class="form-control" placeholder="Search your {{data.selectedOption.name}} here..." />
        <div ng-show="true">
          or directly select your choice here...
          <select name="subSelect" id="subSelect" ng-options="option.name for option in data2.availableOptions2
        track by option.id" ng-model="data2.selectedOption2"></select>
          <br/>
          <button style="color:#757575" ng-click="search()">
            ...and go!</button>
        </div>
      </div>
    </form>

    <!--RESPONSE-->
    <div ng-controller="ctrl" ng-show="true">
      <p>{{response}}</p>
    </div>
  </div>
</body>

</html>

Despite attempting various solutions, the view does not update when modifying $scope.response in this example... and alert($scope.response) confirms that the button functionality is intact... Utilizing methods like $interval, $timeout, $apply, $watch have proved unsuccessful in resolving the issue. Any insights would be greatly appreciated.

Thank you for your assistance.

If this query has been previously addressed, I apologize as I couldn't locate a resolution.

Answer №1

You are re-instantiating the controller, causing it to be recreated and resulting in an undefined response. Remove

 <div ng-show="true"> //remove ng-controller
      <p>{{response}}</p>
 </div>

Here is a working snippet:

(function(angular) {
      'use strict';
      angular.module('app', [])
        .controller('ctrl', ['$scope', function($scope) {
          $scope.init = function() {
            $scope.response = "press the button";
          }();

          $scope.data = {
            availableOptions: [{
              id: '1',
              name: 'num'
            }],
            selectedOption: {
              name: 'selected field'
            }
          };

          $scope.data2 = {
            availableOptions2: [{
                id: '0',
                name: 'null'
              }
            ],
            selectedOption2: {
              name: 'null'
            }
          };

          $scope.search = function() {
            $scope.response = "you pressed a button \\o/";
            alert($scope.response);
          };

          $scope.request = function(req) {
            $http(req).then(function() { /*successCallback*/ },
              function() { /*errorCallback*/ });
          };

        }]);
    })(window.angular);
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="//code.angularjs.org/1.7.3/angular.min.js"></script>
  <script src="analyzer.js"></script>
</head>

<body ng-app="app" ng-controller="ctrl" >
  <div ng-show="true">
    <!--class="ng-hide" is automatically added when ng-show="false"-->

    <!--SEARCH-->
    <form name="myForm">
      <label for="mySelect">Select a field:</label>
      <select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>
      <br/>
      <div style="color:#757575">
        <input ng-model="query" type="text" size=45 class="form-control" placeholder="Search your {{data.selectedOption.name}} here..." />
        <div ng-show="true">
          or directly select your choice here...
          <select name="subSelect" id="subSelect" ng-options="option.name for option in data2.availableOptions2
        track by option.id" ng-model="data2.selectedOption2"></select>
          <br/>
          <button style="color:#757575" ng-click="search()">
            ...and go!</button>
        </div>
      </div>
    </form>

    <!--RESPONSE-->
    <div ng-show="true">
      <p>{{response}}</p>
    </div>
  </div>
</body>

</html>

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

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

``When multiple elements are clicked, the second click will remove the class

I'm struggling with jQuery. Essentially, I want the first click on "div 1" to add a class to the others and display "lorem ipsum" text, and continue this pattern for the rest. However, if I click on the same div again, the class should be removed and ...

Karma: Uncaught ReferenceError - You must define the app before using it

I recently followed a tutorial on for testing AngularJS applications with Karma. This is how my karma.conf.js file appears: module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

What is the correct way to establish a backgroundImage path in React JS?

When adding an img, the image path functions as expected: import Background from "./img/bg.webp"; ... <div> <img className='bg' src={Background} /> </div> However, when using the same path for the backgroundImage property, ...

Having trouble updating the icon on my website using FontAwsome

Just a heads up - I'm not familiar with HTML/CSS/JS. This template is pre-made, and I'm simply making some adjustments to it. Hello, I'm currently working on my portfolio website and I want to display my projects based on the programming la ...

Dispatch an angular POST Request

I am facing an issue where Angular is sending a GET request instead of a POST request when I want to send a post request. The code for my Angular request is as follows: $http({ method: 'POST', url: pages_url, params: { ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

Creating a JavaScript anchor through a backend bean function

Is it crazy to want to create an anchor that can be called from a backing bean method using JavaScript? I need to do this for specific reasons, utilizing a commandButton with ajax set to false. I'm attempting the following approach: RequestContext.g ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

Can JavaScript be used to update/override Prototype version 1.4 to version 1.7 on a different website?

(I'm uncertain about the best way to phrase this question, feel free to make changes). I am in the process of embedding a JS widget onto a different website that is using Prototype.js Version 1.4. I have incorporated jQuery into my widget and have it ...

Leveraging packages obtained from npm repositories

Recently, I came across this guide about React that included a paragraph that left me puzzled. According to the guide, CommonJS modules (found in npm) cannot be directly used in web browsers due to technical limitations. Instead, you need a JavaScript " ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Adding methods to a constructor's prototype in JavaScript without explicitly declaring them

In the book Crockford's JavaScript: The Good Parts, there is a code snippet that demonstrates how to enhance the Function prototype: Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; Crockford elabo ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...