Steps for dynamically changing views in AngularJS and updating the list contents

Brand new to this world! Have a look at my html & js code below. Pressing "Add" friend but facing the following hurdles:

  1. $scope.friends list remains untouched. $scope.newFriend.name, $scope.newFriend.age end up as undefined.
  2. Also seeking guidance on how to refresh view1 to display the updated list.

----- main.html -----

<!doctype>
<html>
<body>
<div ng-app="demoApp" ng-controller="FriendsController">
  <input type="text" ng-model="name">
  <p>I'am {{name}} have {{friends.length}} friends. </br>They are:</p>
  <input type="search" ng-model="search" placeholder="Find by name/age/gender" /> | <a href="#/add">Add Friend</a>
  <div ng-view></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js">      </script>
<script src="Scripts/angular-route.js"></script>
<script>
 var demoApp = angular.module('demoApp', ['ngRoute']);

 demoApp.config(['$routeProvider',
  function($routeProvider) {
$routeProvider.
  when('/', {
    templateUrl: 'view1.html',
    controller: 'FriendsController'
  }).
   when('/add', {
    templateUrl: 'view2.html',
    controller: 'FriendsController'
  }).
  otherwise({
    redirectTo: '/'
  });
}]);

 demoApp.controller('FriendsController', function($scope){
$scope.name = "Joeey";
$scope.newFriend = {};
    $scope.friends = [
  {name:'John', age:25, gender:'boy', sal :100},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Pabtrgick1', age:40, gender:'boy'},
  {name:'Pabtrgick2', age:40, gender:'girl'},
  {name:'Samantha', age:60, gender:'girl'}
];

$scope.addFriend = function(){
  $scope.friends.push({
    name : $scope.newFriend.name,
    age : $scope.newFriend.age,
    gender : $scope.newFriend.gender
  })
  console.log($scope.friends);
}
});

</script>
</body>
</html>

---- view1.html ---

<ul>
<li  ng-repeat="f in friends  | filter:search | orderBy:'name'">
  [{{$index + 1}}] {{f.name | lowercase}} - {{f.gender | uppercase}} is {{f.age}} years old & salary is {{f.sal}}.
</li>
</ul>

---- view2.html ---

<br/>Name: <input type="text" ng-bind="newFriend.name" />
<br/>Age: <input type="text" ng-bind="newFriend.age" />
<br/>Gender: <input type="text" ng-bind="newFriend.gender" />
<br/><button ng-click="addFriend()">Add</button>

---- EDIT (Added factory method & modified FriendsController) ---

demoApp.factory('friendsFactory', function(){
 var friends = [
  {name:'John', age:25, gender:'boy', sal :100},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Pabtrgick1', age:40, gender:'boy'},
  {name:'Pabtrgick2', age:40, gender:'girl'},
  {name:'Samantha', age:60, gender:'girl'}
];
var factory = {};
factory.getFriends = function(){ return friends};

return factory;
 });


demoApp.controller('FriendsController', function($scope, $location, friendsFactory){
$scope.name = "Joeey";
    $scope.friends = friendsFactory.getFriends();

$scope.addFriend = function(){
  $scope.friends.push({
    name : $scope.newFriend.name,
    age : $scope.newFriend.age,
    gender : $scope.newFriend.gender
  })
  $location.url('/')
}
});

Answer №1

1). It is recommended to separate concerns by handling the listing of friends and adding a new one in two different controllers: FriendsController and NewFriendController.

2). A custom service like Friends would be ideal for sharing the friends array.

3). Use ng-model instead of ng-bind to pass form data back to the controller.

4). To redirect to another route, utilize the $location service: $locations.route('/').

Here's an example implementation:

demoApp.factory('Friends', function() {
    var friends = [{
        name: 'John',
        age: 25,
        gender: 'boy',
        sal: 100
    }];
    return {
        getAll: function() {
            return friends;
        },
        addNew: function(friend) {
            friends.push(friend);
            return this.getAll();
        }
    };
});

demoApp.controller('FriendsController', function($scope, Friends) {
    $scope.name = "Joeey";
    $scope.friends = Friends.getAll();
});

demoApp.controller('NewFriendController', function($scope, Friends, $location) {
    $scope.addFriend = function() {
        Friends.addNew($scope.newFriend);
        $location.path('/');
    }
});

Demo: http://plnkr.co/edit/1fPCavXuqhkyH2lrue2c?p=preview

Having a Friends service makes it easy to extend functionality and integrate with remote databases or REST APIs.

Answer №2

To ensure data sharing between views, either utilize a service or centralize controller declarations at the top-level ng-controller. Avoid using ng-bind for two-way binding; stick to ng-model for input elements.

An example highlighting synchronized fields when utilizing a shared controller versus independent instances can be seen here.

Don't forget to inject $location and implement $location.path('/') in addFriend() to navigate back to view1 as suggested by others.

Answer №3

Your errors are just simple typos, make sure to refer to the Angular Docs

  1. When binding input values to Angular $scope variables, remember to use the ng-model attribute instead of ng-bind. ng-bind is specifically for displaying values, while ng-model does what you need it to do.

  2. To navigate to view1 after adding a friend, simply call $location.url('/') in your $scope.addFriend method. And don't forget to inject $location into your controller.

Answer №4

Whenever you modify the scope's value, it is necessary to use $apply to implement those modifications.

$scope.addToDo = function(){
  $scope.$apply(function() { 
        $scope.todos.push({
              task : $scope.newTask.task,
              priority : $scope.newTask.priority
        });
   });
}

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

Unable to retrieve a single item in NextJS

Struggling with fetching a single item in NextJS const PRODUCT_API_BASE_URL = "http://localhost:8080/api/v1/products/"; export const getStaticPaths = async () => { const res = await fetch(PRODUCT_API_BASE_URL); const data = await res.json(); ...

tips for building angularjs widgets with limited scope

Is there a way to generate widgets from HTML scripts on a webpage? For example: <script type="text/html" id="widget-simple"> <div class="widget-simple"> This is my widget and its name is {{ test }} </div> </script> & ...

The proper naming convention must be followed when defining functions in AngularJS Services

I'm in the process of creating a demonstration application using AngularJS and I want to incorporate a factory into it as well. Unfortunately, I keep encountering an error message that says: "SyntaxError: function statement requires a name". Here is ...

Retrieve data from REST call to populate Material dropdown menu

I am looking to dynamically populate a dropdown menu with data retrieved from a Rest API. I attempted the following code: <Select id="country-helper"> {array.map((element) => ( <MenuItem value={element.code}>{element.country}& ...

Troubleshooting: Success with AJAX call in Chrome, but issues in IE

Having issues retrieving JSON data from a URL that displays the last 3 numbers of a webpage. The AJAX call functions correctly in Google Chrome but fails in Internet Explorer. I tried disabling caching using cache: false as suggested, but the problem persi ...

Use the toggle function in pure JavaScript to apply it only to the element that has been clicked

In this HTML code snippet, I am displaying data in a list format with nested subcategories. Each category is displayed as a clickable parent menu item. When clicked, the corresponding subcategories should be toggled to show or hide. <ul id="menu"&g ...

Implementing a delete functionality within a loop on a JavaScript object array

I have a JavaScript object with the following structure: var partner = { p_name: { value: partner_name, label: "Name" }, p_id: { value: partner_ID, label: "ID" }, p_status: { value: partner_status, label: "Status" }, p_email: { value: partner_emai ...

Exploring Angularjs End-to-End Testing using Angular-UI's Select2 Component

I am facing a challenge with a partial that has a select2 element using Angular UI http://angular-ui.github.io/ The problem is that the element is marked as required, and even though I have managed to set the field through the code provided below, the req ...

What could be causing my item-list to malfunction in Vue.js?

I recently attempted to develop my own Vue.js application by following the provided documentation. Unfortunately, I encountered an error that has proven difficult to resolve. Despite my efforts to recreate the app as instructed, the list does not show an ...

What is the best way to incorporate auto refresh in a client-side application using vue.js?

Disclaimer: I have separated my client application (Vue.js) from the server side (DjangoRest). I am utilizing JWT for validating each request sent from the client to the server. Here is how it works - The client forwards user credentials to the server, an ...

The relative link feature in React Router fails to properly navigate

Currently, I am utilizing the npm package react-router-relative (https://www.npmjs.com/package/react-router-relative) for my project. However, it seems to be having trouble properly switching the URL. Here is how my links are configured: <Link to=&apo ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

How can I make $.when trigger when a JSON request fails?

I am currently using the code below to retrieve JSON data from multiple URLs. However, I have noticed that if one of the URLs fails or returns a 404 response, the function does not execute as expected. According to the jQuery documentation, the "then" fu ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Using Angular, update the text of a button depending on the selected radio button option

After developing an angular application with 2 radio controls and a text button, I am looking to implement changes in the button text based on specific conditions. 1. The text of the button should switch between 'Upgrade' or 'Save' dep ...

Utilize the map function on an array object to present data in a table using React framework

My parent component passes an array object that looks like this: https://i.sstatic.net/Nqh81.png I want to organize these values into a table with the keys in one column and their corresponding values in other columns. The desired format is shown here: ht ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Swap out the <a> tag for an <input type="button"> element that includes a "download" property

I have been working on a simple canvas-to-image exporter. You can find it here. Currently, it only works with the following code: <a id="download" download="CanvasDemo.png">Download as image</a> However, I would like to use something like th ...

The set operator in Firestore does not append any new documents to the collection

I recently implemented a promise chain to store user data in Firestore and handle authentication, but I encountered an issue. Initially, I used the add operator to save the data, but later decided to assign users based on their unique UID. After making thi ...

PHP script for batch string replacement

My function is triggered by a button click, where it takes two input IDs and forms a string as follows: var str = "headingText=" + $("#headingText").val() + "&centerText=" + $("#centerText").val(); $.ajax({ url: "indexpdf.php", data: str, ...