Exploring AngularJS's Unique Features: Isolated Scope and Controller Connection

Currently, I am diving into Angular and endeavoring to develop a Phone Message Log application utilizing directives. The concept is simple - the user inputs a message, clicks a button, and it gets displayed in a "Message" log below.

The challenge I'm facing is incorporating the date of the message using a getDate() method within the controller. However, I observe that each time a new message is added, all dates get overwritten. My assumption is that this issue stems from shared scope, but I'm unsure how to resolve it.

To see an example, check out this fiddle: http://jsfiddle.net/dgalati/qpo87d31/

<div ng-controller="AppCtrl">
<phone number="000 000 0000" make-call="addToMessageLog(number, message)"></phone>
 <h1>Message Log</h1>

<li ng-repeat="message in messageLog"><b>Date:</b> {{getDate()}} <b>Message:</b> {{message}}</li>
</div>

var app = angular.module("phoneApp", [])

app.controller("AppCtrl", function ($scope) {
$scope.getDate = function () {
    return new Date();
}
$scope.messageLog = [];

$scope.addToMessageLog = function (number, message) {

    //alert(number + " " + message)
    //alert(message);
    $scope.messageLog.push(message);
    for (var x = 0; x < $scope.messageLog.length; x++) {
        console.log($scope.messageLog[x]);

    }
}

})


app.directive("phone", function () {
return {
    restrict: "E",
    scope: {
        number: "@",
        network: "=",
        makeCall: "&"
    },
    template: '<input type="text" ng-model="value" style="width:350px;">' +
        '<div class="button" ng-click="makeCall({number:number, message:value})">Call {{number}}     and leave a message</div>',
    link: function (scope, element, attrs) {


    }

}

})

Answer №1

When displaying messages in your application, it's important to consider the logic behind how they are shown. Each time a message is typed, the ng-repeat directive re-evaluates and the getDate() function is also re-evaluated because it is used within the ng-repeat. To ensure that the date of each message is attached to the message object itself, you can refer to my code snippet on this link.

<li ng-repeat="message in messageLog track by $index"><b>Date:</b>
{{message.date}} <b>Message:</b> {{message.content}}
</li>

With this adjustment, each object in messageLog includes both its content and timestamp:

$scope.messageLog.push({content:message,date:new Date()});

The use of the "track by" expression is essential for distinguishing between items and avoiding duplicate errors in the ng-repeat iteration.

Answer №2

Avoid combining getDate with ng-repeat to prevent unnecessary DOM rerendering and function evaluation each time messageLog is altered.

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

Guide to utilizing the app.locals parameter in JavaScript?

Currently I am in the process of developing a node.js application. In my app.js file, I have loaded a JSON file as app.locals.parameter and now I am attempting to utilize it in my index.hbs. Let's assume: app.locals.componentData = require('./m ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

The expected result is not obtained when making an Ajax request to a PHP variable

I recently encountered an issue with my AJAX GET request. The response I received was unexpected as the PHP variable appeared to be empty. Here is the snippet of jQuery code that I used: jQuery(document).ready(function($) { $.ajax({ url: '/wp ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

The JQuery datepicker fails to display the current date

I am experiencing an issue with the datepicker on my webpage. While it is working correctly, the default date being displayed is '01/01/2001' instead of '11/23/2012', as I intended. Here is the jquery code I am using: $(":inpu ...

What methods can I use to get my kahoot botter to produce unpredictable answers?

After attempting to create a kahoot botter using the updated kahoot.js library, I came across this code snippet that supposedly answers random questions: const Kahoot = require("kahoot.js-updated"); var kahoots = [] for (var i = 0; i < bot_cou ...

Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue, I am attempting to create something like this: input key 1 , input value 1 input key 2 , input value 2 < button to add more > < submit button > Essentially, a user can click submit and send a Get req ...

Discovering common elements in various arrays of objects

Details: record1 = [{"site": "The Blue Tiger", "zipcode": "E1 6QE"}, {"site": "Cafe Deluxe", "zipcode": "E6 5FD"}] record2 = [{"site": "Blue Tiger", "zi ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Developing a dynamic modal using Angular and embedding Google Maps within an iframe

I'm currently working on implementing a modal in my Angular application that, when opened, displays Google Maps within an iframe. The problem I'm facing is that the iframe isn't loading and I'm receiving this error in the browser conso ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

Exploring the intricacies of JSON data in AngularJS

I am new to AngularJS and familiar with working with basic JSON data using AngularJS. I have complex JSON data that I need to work with. [ { "activity_user": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="09687a6d ...

Use jQuery to set a Firebase image as the background of a div element

Is there a way to fetch an image from Firebase and use it as the background for a div element? I've tried several approaches without success. Could someone share some examples on how to achieve this? <div class="museBGSize rounded-corners grpelem" ...

What could be the reason for the datepicker popup failing to appear?

I am currently working on developing a custom bootstrap datepicker directive: app.directive('datePicker', function ($compile, $timeout) { return { replace: true, restrict:'E', templateUrl: 'datepicker.h ...

The issue of missing content within nested views in Ionic is a common problem

I am currently working on nesting views with ionic v1.3, and here is some of the parent HTML code: <h2>welcome </h2> <ion-nav-view name="welcomeCreate"></ion-nav-view> <ion-nav-view name="welcomeJoin"></ion-nav-view& ...

Using a while loop to chain promises in webdriver.io

I am trying to capture a full webpage screenshot by taking tiles of the viewport size. I have almost completed this task, but I am relatively new to promises and need guidance on the correct approach. Below is my code. The issue I am facing is that the ca ...

Struggling to import MUI components from node modules in your React JavaScript project using Vite? Discover why autosuggestion isn't getting the

Encountering a dilemma with autosuggestion in Visual Studio Code (VSCode) while attempting to import MUI (Material-UI) components from node modules in my React JavaScript project built with Vite. The autosuggestion feature is not working as intended, causi ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Is it possible to utilize Jquery in order to add an opening <tr> tag and a closing </tr> tag within a dynamic table?

I have been experimenting with the code snippet below in an attempt to dynamically add a closing </tr> tag followed by an opening tag after every three cells, essentially creating a new row. Progress has been made as the DOM inspector shows a TR nod ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...