Using Angular's filter service within a controller

Just starting out so please be kind!!

Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller.

In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the custom filter gets updated (e.g., due to a service update), only the inline ( {{ }} ) filter reflects the changes on the view.

Check out the Plunkr here: http://plnkr.co/edit/nukioL3ORnl9KDPHmNoY?p=preview

(function(angular) {
  'use strict';
  angular.module('myStatefulFilterApp', [])
    .filter('decorate', ['decoration',
      function(decoration) {

        function decorateFilter(input) {
          return decoration.symbol + input + decoration.symbol;
        }
        decorateFilter.$stateful = true;

        return decorateFilter;
      }
    ])
    .controller('MyController', function($filter, $scope, decoration) {
      $scope.greeting = 'hello';
      // This will update
      $scope.decoration = decoration;
      // This won't
      $scope.code = $filter('decorate')($scope.greeting);
    })
    .value('decoration', {
      symbol: '*'
    });
})(window.angular);

I've experimented with different solutions for this issue, including event listeners, but it seems that none of those will solve the problem.

This problem initially arose from using the date filter and the locale plugin that dynamically updates the locale, resulting in the filter not updating when the locale changes.

Any suggestions on how to make the code-based filter monitor changes (possibly using a $watch task) are greatly appreciated.

Thanks in advance.

- Adam

Answer №1

When it comes to the controller, it is executed just once and not every single time the scope updates. The expression

$filter('decorate')($scope.greeting)
gets evaluated during the assignment to $scope.code, whereas {{greeting | decorate}} gets evaluated whenever the scope updates.

If your filter isn't marked as stateful, then the filter expression {{greeting | decorate}} will only get evaluated upon updating of greeting. However, all this does not impact the behavior within the controller.

To ensure that $scope.code gets updated every time there is a change in $scope.greeting, you can use $scope.$watch:

$scope.$watch('greeting', function(newValue) {
    $scope.code = $filter('decorate')(newValue);
});

Answer №2

    Have you considered using the $watch method? It could potentially solve your issue.

    Check out the updated code snippet below:

http://plnkr.co/edit/4IlBIhh2JfmPcMDW0ty6?p=preview

    Hopefully, this suggestion proves helpful to you.

    Appreciate it!

Answer №3

I came up with a solution that doesn't involve using $watch, instead utilizing a function attached to ng-change in the input field.

  $scope.update = function(){
    $scope.code =$filter('decorate')($scope.greeting);
    };

Check out my solution on Plunker here

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

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

Preventing Context Menu from Appearing on Long Click in HTML5 Games

I'm attempting to utilize a similar technique as demonstrated in this stackoverflow post: How to disable the 'save image as' popup for smartphones for <input> However, I am encountering an issue where my button is not displaying at ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

What could be causing npm to not recognize my module in the "require" statement?

Currently, I am in the process of developing an npm module and conducting tests before making it available to the public. The method I am following is outlined in a blog post found at this link. However, I am encountering difficulties when trying to requir ...

Error encountered in React JS: The property being accessed is undefined and therefore cannot be mapped

I have been working on a MERN project and I am currently at the stage where I am integrating the frontend and backend using Axios. However, I have encountered some issues. One of the most common errors I am facing in my list screens is: TypeError: Cannot r ...

Is it necessary for me to use bindActionCreators?

While going through a post, I couldn't help but notice that the bindActionCreators method from redux wasn't being utilized. Is there a specific reason for this? Could it be that the method is not necessary in this context? The post in question ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

Appending the desired URL to the existing URL using an Ajax callback

Ever since I started working on a Drupal 7 project, I have been facing an issue with making an ajax call back. The problem arises when the URL I intend to use for the callback gets appended to the current page the user is viewing. It's quite puzzling ...

I am experiencing an issue where the submit button in my HTML form is unresponsive to clicks

Welcome to my HTML world! <form action="petDetails.php" id="animalInput"> <ul> <li> <label for="dogName">Enter Dog's Name:</label><input id="dogName" type="text" name="dogName" /> </l ...

Manipulate the contents of children divs within a parent div using JavaScript or JQuery

<div id="abc"> <div id="a_b"> abcd </div> <div id="c_d"> xyz </div> </div> I have a challenge where the divs on my page are generated dynamically and their IDs change every time the page loads. When the window i ...

Updating a $scope variable within a loop in AngularJS

Attempting to modify a $scope variable: Example: $scope.variable_1 $scope.variable_2 ... Desired way of updating it: for (i=0; i<2; i++) { $scope.variable_$i = 1; } Wanting to access "$scope.variable_1" using the "i" index in each loop. Any ...

How can we automate the process of assigning the hash(#) in Angular?

Is it possible to automatically assign a unique hash(#) to elements inside an ngFor loop? <div *ngFor="let item of itemsArray; index as i"> <h3 #[item][i]> {{ item }} </h3> </div> I would like the outp ...

Incorporate Object names and Variable names in Javascript programming

I have an object named res and a variable named lea. I need to concatenate. For example: let lea = "abc"; let res = { abc:'steve' }; console.log(res.lea); So my output should be steve. I tried it like this: console.log(res.`${lea}`); ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Resuming AJAX requests after being aborted

Hey everyone, I'm curious to know if it's possible to resume interrupted ajax requests. I have an array of ajax calls stored as defferreds like this: var defferreds = []; defferreds.push( $soap.ajax({ type: "POST", dataType: ...

Delete ObjectId from Array using Node and Mongoose

Currently, I am working on a website that features a comments section for campsites. This platform is similar to Yelp but focuses on reviewing campsites. Each campsite in the MongoDB collection has a field called "comments" which stores the IDs of all comm ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...