Updates to AngularJs models are not being reflected

I am facing an issue with my model that I want to make editable, but for some reason nothing changes - the textbox fails to appear and the model remains unchanged when using ng-view.

I can confirm that the function enableEditor() is being triggered as I see it in the console log.

If I include the code inline in the index.html without the profile.html, everything works perfectly fine.

Below are the relevant files:

app.js

var proGamersApp = angular.module('proGamersApp', ['ngResource']).
    config(function ($routeProvider) {

        $routeProvider.
        when('/', { controller: 'ProfileController', templateUrl: '/app/partials/profile.html' }).
        otherwise({ redirectTo: '/' });
    });

var ProfileController = function ($scope) {

    $scope.init = function () {
        $scope.title = 'first title';
    };

    $scope.init();
    $scope.enableEditor = function () {
        console.log('enableEditor()')
        $scope.editorEnabled = true;
        $scope.editableTitle = 'second title';
        $scope.title = 'second title';
    };

     ...
};

index.html

<!doctype html>
<html ng-app="proGamersApp">
<head>
    <title>Pro Gamers</title>

    <!-- Scripts -->
    <script src="/app/lib/angular.min.js"></script>
    <script src="/app/lib/angular-resource.js"></script>
    <script src="/app/app.js"></script>

</head>
<body>
    <div ng-view></div>
</body>
</html>

profile.html

 <div ng-hide="editorEnabled">
        {{title}}
      <a href="#" ng-click="enableEditor()">Edit title</a>
    </div>
    <div ng-show="editorEnabled">
        <input ng-model="title" ng-show="editorEnabled">
        <a href="#" ng-click="save()">Save</a>
        or
      <a href="#" ng-click="disableEditor()">cancel</a>.
    </div>

Can anyone help me identify what I might be doing wrong?

Thank you

Answer №1

The URL is being added to your address, which causes the router to refresh the page and reset all of your $scope variables. Instead of using empty anchor tags, try using a span styled to look like an anchor:

span:hover {
    cursor:pointer;
}

This will change the cursor to a pointer when hovering over the span. Feel free to customize the colors as you see fit. Also, based on your comments, don't include target=_self in the href attribute; instead, add it after the tag:

<a href="#" target=_self ng-click="save()">Save</a> //prevents changing the address bar

However, I recommend sticking with spans instead.

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

Error 400: Invalid Request: Issue encountered when swapping code for Asana access token using Next.js

Encountered a 400 Bad Request error while trying to exchange the code for an access token at . I am unsure of the cause and would appreciate any assistance. Below is the code: const GetAsanaAccessToken = async (req, res) => { const body = { grant ...

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

How to handle an InputStream with zero file length in Java using the Spring framework

I am facing an issue with my REST application that has a client implemented in Angular and a server built with Spring. When I try to send a file using an async request, I end up receiving a 0-length file. It's perplexing because the header displays th ...

What is the best way to have child controllers load sequentially within ng-repeat?

Currently, I have a main controller that retrieves data containing x and y coordinates of a table (rows and columns). Each cell has a child controller responsible for preparing the values it will display based on the x and y values from the parent control ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

Move the focus to the previous input field by removing the key

I have created a phone number input with 10 fields that automatically skip to the next field when you fill in each number. However, I would like to be able to go back to the previous field if I make a mistake and need to delete a digit. How can I achieve ...

Solving Addition and Subtraction Errors in Javascript/Jquery

Upon running the script below, it aims to calculate the height of the browser, as well as the heights of both the header and footer, subtracting them from the initial browser height: var a = $(window).height(); alert (a); var b = $('#header').cs ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Activate the jQuery click event by specifying the URL

On my webpage, I have a jQuery click function that loads multiple HTML pages into a specified div. I am looking to set specific URLs that will trigger this event, like test.com#about <script type="text/javascript"> $(document). ...

Stryker score caused the Jenkins build to fail

Is there a way to configure the Jenkins pipeline so that it fails when the stryker score is below X? This is the stryker configuration: config.set({ mutator: "javascript", mutate: [...], testRunner: "jest", jest: { projectType: "n ...

The setInterval() function within a jQuery dialog continues running even after being destroyed or removed

I'm facing an issue with a jQuery dialog that loads an external page and runs a setInterval() function querying the server continuously every second via AJAX. The problem arises when I close the dialog, as the setInterval keeps running. Below is the ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

Ways to Increase jQuery Element ID

I have several instances of jPlayer (a jQuery audio player) set up: jPlayer1, jPlayer2, jPlayer3, jPlayer4. Each one is initialized and preloaded with audio files. The following function will loop through an existing array and attach a method to play the ...

What is the best way to invoke a controller method using jQuery within a cshtml file?

I am working on a project where I need to add user information to the database by calling a function in my controller class. The user's information is entered through a form created in a .cshtml file that interacts with an external JavaScript file. Is ...

Execute the function within setInterval only one time

I have a setInterval function that calculates the time difference between a specified date and the current time. Once this difference is less than an hour, I want to execute some code only once. const countdownDate = new Date('March 15, 2021 11:30:00& ...

Place background image in the center with a background color overlay

After browsing through this post on Stack Overflow, I managed to stretch my background image using CSS with the background-size: cover; property. However, I realized that this solution doesn't completely meet my needs. I'm dealing with an image ...