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

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

JavaScript never forgets to validate the user input

Forgive me for my lack of experience, but I am new to this and seeking guidance. I am struggling to find a straightforward example on how to validate HTML input using JavaScript. Currently, I am working on a search function and need help in implementing ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Scope binding is successful, but accessing the array is only possible after adding an Alert() function

Within my Angular controller, I'm utilizing the SharePoint JavaScript Object Model to fetch data from the Taxonomy (term store). Due to SharePoint's JSOM not being a conventional Angular function that can be easily understood by the scope, I util ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

Cease the execution within the promise.then block

Embarking on my nodejs journey has been an exciting experience. While I have a background in other programming languages, the concept of promises is new to me. In my nodejs environment, I am using expressjs + sequelize. I'm currently working on setti ...

Is there a way to potentially utilize window.open() to open a specific section of a webpage?

My HTML page consists of 2 div blocks and 2 links. I want to open the content of the first div in a new window when the first link is clicked, and the content of the second div in another new window when the second link is clicked. You can find the code h ...

Ways to locate two div class elements that are generated dynamically

I am looking to dynamically create 2 divs in different locations. One for displaying information and another for editing information. I want to be able to delete both divs with the same class when using the delete button. Since they are located in differe ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

I am attempting to achieve a smooth transition effect by fading in and out the CSS background color using JQuery and AJAX

Can anyone help me with my issue related to using Ajax to fadeIn a background color in beforeSend and fadeOut in success? I seem to have made some mistakes but can't figure out what went wrong. var data={ ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Merge requirejs modules using build script

I am attempting to merge and compress require modules into a single file. For instance, if I have a file named article.js with the following content: define(["jquery","flexslider","share_div"],function(){}); I wish for all these dependencies to be merge ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

Combining Turn.js with AJAX for an interactive web experience

I've been experimenting with turn.js and struggling to find an example of loading dynamic pages with content via ajax. While the page is loading, it's not displaying all the results. For a JSON result from the controller, click here. <div clas ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Tabulator - Using AJAX to retrieve a JSON document

I am currently working on importing a json file from an Azure blob container using Azure Data Factory. Despite closely following the documentation and researching various resources on Stack Overflow, I am facing challenges with making the ajax request fun ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...