Exploring the world of Angular JS with its powerful directives, the magic of ng-repeat functionality,

Hello all, I am new to Angular so please bear with me if I make any mistakes in the terminology.

Below is a simple example where I am trying to bind a template in a directive within an ng-repeat. When updating the input field, {{list.name}} gets updated but the {{formattedtext}} does not change.

How can I make sure that the formatted text reflects the correct value?

HTML

<div ng-repeat="list in List" style="border: 1px solid;">
    <list-item>
    </list-item>
</div>
<div ng-repeat="list in List" style="border: 1px solid;">
    <input ng-model="list.name" />
</div>

app.js

referenceController.$inject = ['$scope'];

var app = angular.module('app',[]).controller('referenceController', referenceController);

app.directive("listItem", function () {
    return {
        restrict: "E",
        scope: false,
        template: "<div>Yo {{formattedText}} {{list.name}}</div>",
        link: function (scope, element, attrs) {
        scope.formattedText = scope.list.name + ' (' + scope.list.abbreviation + ')';
        }
   }
}); 

referenceController.js

function referenceController($scope) {
    $scope.List = [
        { id: 1, name: 'Name1', abbreviation:'1'},
        { id: 2, name: 'Name2', abbreviation: '2'},
        { id: 3, name: 'Name3', abbreviation: '3'},
        { id: 4, name: 'Name4', abbreviation: '4'}
    ];
}

Answer №1

Deriving formattedText is a simple task that can easily be included in the template like so:

template: "<div>Hey {{list.first}} ({{list.second}}) {{list.third}}</div>"

Answer №2

Make sure to keep an eye on the value within your directive:

referenceController.$inject = ['$scope'];

var app = angular.module('app',[]).controller('referenceController', referenceController);

app.directive("listItem", function () {
  return {
    restrict: "E",
    scope: false,
    template: "<div>Hello {{formattedText}} {{list.name}}</div>",
    link: function (scope, element, attrs) {
      var formatText = function(value){
        scope.formattedText = value + ' (' + scope.list.abbreviation + ')';
      }

      formatText(scope.list.name)
      scope.$watch('list.name',formatText)
    }
 }
}); 

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

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

What is the best way to display a hidden ng-repeat item that is already hidden?

I have a list that is displayed using ng-repeat: <div class="name" ng-hide="name.hide" ng-repeat="name in nameArray" ng-click="checkName(name)"> When one of the items in the list is clicked, I want it to be hidden. In my controller, I'm handli ...

Adjusting the field of view of a perspective camera in THREE.JS while maintaining the camera's original distance

My ultimate goal is to adjust the FOV value of my camera while triggering an animation. However, upon implementing the FOV value changes, I notice that my scene appears smaller. This has led me to question the mathematical relationship between the FOV val ...

Are there any JavaScript functions available that can navigate to a different HTML page?

Here is an example of the functionality I am attempting. Can it be implemented? function CloseHTML(){ ApplyCSSClosingTransition(); setTimeout(function() { RedirectToAnotherPage(); }, 2000); } <div onClick='CloseHTML()'&g ...

Refresh a specific div element within an HTML file when the AJAX call is successful

After uploading the image, I want it to be displayed right away. To achieve this, I am looking to refresh the div with id="imagecontainer" within the success function of my ajax call. However, I would prefer not to rely on ("$id").load("href") as it does ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

Switching between different CSS files based on the URL using jQuery or another method

Is it feasible to apply specific styles based on the ID or load various CSS files depending on the URL you are visiting? For example: <script> if(location.href == 'http://jpftest2.tumblr.com/about'){ document.write('<style type= ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

What is the best way to retrieve the column that comes after a specific column?

I have a specific column and I want to extract the subsequent column in the dataset. nhood,column,variablecolumn Treasure Island,3,5 McLaren Park,1,2 Tenderloin,28,112 Lakeshore,14,8 Chinatown,15,103 Although I know the name of the second column, the na ...

Having trouble setting cookies with Node.js Express?

Check out this code snippet: const app = express(); const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.post("/pinfo", (req, res) => { var form = new formidable.IncomingForm(); form.parse(req, async functi ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

"Ajax has the ability to alter the vertical scroll position

I have a quick query for you. Can anyone assist me in understanding why the page scroll resets to the top after an Ajax request? I suspect it has something to do with JQuery. There isn't much information available online, so I'm reaching out for ...

Gridlines Collapse upon Rendering in the Griddle Subgrids

Griddle has the capability to support subgrids. In one of the fields, I have a customized component for row selection that triggers a state change. This state change leads to a re-rendering of the component, causing the collapse of the subgrid. However, I ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

Tips for displaying the most recent data in Vue following a successful fetch operation

I have the following script to load data from the server after the page loads: <script> export default { data() { return { imageDirectory: "../../images/", fileName: "img", ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

What's the most efficient method of exporting modules along with their submodules in (Vue, React)?

Looking for the most efficient method to export a module that contains submodules with the help of an index.js? I have been following a specific naming and saving convention for my web components in projects involving Vue or React. However, I am interested ...

Angular6 HttpClient: Unable to Inject Headers in Get Request for Chrome and IE11

Under my Angular 6 application, I am attempting to make a GET request while injecting some custom Headers: Here is how my service is structured: @Injectable() export class MyService { constructor(public httpClient: HttpClient) { } getUserInfos(login): Ob ...