Automatically updating the scope of the .filter() function

Is there a way to update the filter in the code below?

.controller('MainCtrl', ["$rootScope", "$scope", function($rootScope, $scope) {

  $rootScope.number = 1;
  $scope.text = "foo|baz|bar"

}]).filter("MyFormat", ["$rootScope", function($rootScope){
  return function(str){
      return str.split("|")[$rootScope.number]
  }
}])
<button ng-click="$root.number = 0">0</button><!--foo-->
<button ng-click="$root.number = 1">1</button><!--baz-->
<button ng-click="$root.number = 2">2</button><!--bar-->
<pre>{{text | MyFormat}}</pre>

Check out this Plunker example.

Answer №1

Filters in AngularJS always receive the input value as the first argument, but additional arguments can be passed by separating them with a colon within the filter function. For example, I have passed your scope variable number to it.

It is not necessary to use $rootScope; you can simply use the controller scope. When referencing a scope variable in your HTML, you only need to use the variable name without the $scope part. A cleaner version of the code would look like this:

var app = angular.module('MyApp', [])

//Assuming you need to use $rootScope for some reason,
//you can still access it in the HTML as if it were a normal scope variable by just using its name.

  .controller('MainCtrl', ["$rootScope", "$scope",
    function($rootScope, $scope) {

      $rootScope.number = 1;
      $scope.text = "foo|baz|bar"

    }
  ])
  .filter("MyFormat", function() {
    return function(str, num) {
      return str.split("|")[num];
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
  <div ng-controller="MainCtrl">
    <button ng-click="number = 0">0</button>
    <!--foo-->
    <button ng-click="number = 1">1</button>
    <!--baz-->
    <button ng-click="number = 2">2</button>
    <!--bar-->
    <pre>{{text | MyFormat : number}}</pre>
  </div>
</div>

Answer №2

UPDATE: Link has been refreshed

Is this the solution you were looking for?

I have made adjustments to the filter to accept a parameter.

<body ng-controller="MainCtrl">
<pre>{{newText | CustomFormat:number}}</pre>
</body>

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

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Design a circular progress bar with a cut-off at the bottom

Does anyone have suggestions on how to create a circular progress bar with cropping at the bottom, similar to this example: PROGRESS BAR? I've been searching for a component like this but haven't had any luck. Any ideas, especially utilizing Mate ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Step-by-step guide on uploading a local JSON file to Google Maps

I am in the process of creating a map for my website using the Google Maps JavaScript API. The map includes a local JSON layer that outlines a specific polygon area on the map. Everything worked perfectly when I tested it within Visual Studio, but when I t ...

The permission error EPERM is occurring, preventing the copyfile operation from being executed

Need assistance with code execution ionic Cordova build android --prod --release Encountered Error EPERM: operation not permitted, copyfile 'T:\ionic\T\platforms\android\platform_www\cordova-js-src\android\na ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Creating registration and login forms using an express server

Currently, I'm in the process of creating a basic website on my localhost that incorporates a signup form along with other essential HTML elements. The setup for the signup procedure went smoothly as planned. When a user completes the form and submits ...

Dynamic field validation using jQuery

I am currently developing a wizard feature that retrieves employees dynamically from the backend. The employee table is created with a radio input field and then inserted into my HTML code: $.ajax({ method: "get", url: '/fetchEmployees/' ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

How is it possible for the javascript condition to be executed even when it is false?

Despite the condition being false, the javascript flow enters the if condition. Check out the code snippet below: <script> $(document).ready(function() { var checkCon = "teststr2"; console.log("checkCon: "+checkCon); if(checkCon == " ...

Angular 2 Guide on macOS Sierra Shows "Page Not Found" Error in Web Browser

I've been delving into Angular 2 with TypeScript on my OS X machine. Following the tutorial to the T, I didn't encounter any errors during compilation. Upon executing the npm start command, everything seemed to be smooth sailing as a new tab open ...

Determine the percentage of clicks on an HTML5 canvas radial progress bar

Recently, I designed a circular progress bar displaying a specific percentage. However, I am facing a challenge in determining how to calculate the percentage when a user clicks on either the black or green part of the circle. Could you provide insight on ...

Display a series of messages using an Angular directive

Here is a sample HTML code: <section class="correspondence"> <header> <div class="from">{{ message.from }}</div> <div class="when">{{ message.when }}</div> </header> <div class="content"> { ...

Guide on determining the total count based on a specific condition with the help of jQuery

Using AJAX, I have successfully retrieved all status values such as Active, ACTIVE_DRAFT, and Pending. However, I only want to select the statuses that are equal to ACTIVE. To do this, I am using an if condition which is working fine. After filtering by st ...