Creating a custom Angular filter that leverages the power of $http - a

I want to make a retrieval request using $http in AngularJS and then display the obtained result on the front-end. To achieve this, I'm using {{ URL-STRING | iframely }}.

'use strict'

angular.module( 'iframely', [] ).filter( 'iframely', [ '$http', function ( $http ) {
    return function ( url ) {

        var result = $http( {
            url: 'http://localhost:8061/iframely',
            method: 'GET',
            params: {
                url: url
            }
        })

        return( result.then( function ( result ) {
            console.log( result.data.html )
            return result.data.html
        }))
    }
}])

When I view the front-end, all I see is {}, basically an empty object. However, when I check the console log, I can see the correct HTML content.

I am confident that my overall configuration is accurate because if I simply use return "it works", it actually does work. The issue seems to be related to JavaScript scoping, returns, or possibly something specific to $http that I am missing.

Answer №1

Hello Noah,

The reason why the expression is resolving to {} is because the object being returned in the filter definition is actually empty. What is happening is that you are returning a promise and AngularJS is displaying the returned object in your HTML, rather than the resolved value that you may be expecting.

It seems like in this case, you are using AngularJS filters in a way that is not quite appropriate. To achieve the functionality you desire, it would be better to create a directive instead. You can utilize the directive in your HTML like this:

<iframely url="{{ URL-STRING }}"></iframely>

Here is an example of how you could implement the directive in your code:

angular
    .module('app', [] )
    .directive('iframely', ['$http', '$sce', function ($http, $sce) {
        return {
            replace: true,
            restrict: "E",
            scope: {
                url: '@'
            },
            template: '<div ng-bind-html="content"></div>',
            link: function(scope, element, attrs) {
                $http({
                    url: attrs.url,
                    method: 'GET'
                })
                .then(function (result) {
                    scope.content = $sce.trustAsHtml(result.data.html);
                });
            }
    };
}]);

Thank you!

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

Error encountered on production server (Ubuntu 14.04.3 LTS) while running Grunt / npm

Encountering an error on the production server (local environment is working fine on both Windows and OSX). /home/myuser/my-app/node_modules/grunt/node_modules/findup-sync/lib/findup-sync.js:33 }).flatten().uniq().value(); ^ TypeError: undefined is not ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

Is there a method in bootstrap that reveals the elements with the hidden class?

Currently, I am loading data into a bootstrap table on my JSP. The table class is hidden at the moment. After successfully uploading the data into the bootstrap table, I have implemented the following code: $(function() { var table = $('#Table') ...

Display information on the console from any location

I'm working on a Node.js project where I need to display text at specific locations, such as the top right corner. Is there a Node.js module available that can help me achieve this? Something like: var displayModule = require('display_module&ap ...

Customizing row colors in AngularJS ui-grid

I'm facing issues with setting colors for specific rows in Angular ui-grid. I am aware that I can utilize a row template as shown below. However, the "row.sequence" attribute is not working as expected. Could someone provide me with code example ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

"Troubleshooting CSS styling in React material-ui when using withStyles from an external

After reviewing this specific question, I still couldn't figure out how to make it work. The main goal is to keep the styles separate from the component file for a more organized setup. Everything runs smoothly without incorporating a theme. I atte ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

"Injecting the value of a jQuery variable into a PHP variable

<script type="text/javascript"> $(document).ready(function(){ $("#t_select").change(function(){ var table_name = $("#t_select").val(); $.ajax({ type: 'POST', ...

The information being sent from Angular is not being successfully transmitted to the XAM

Here is my Angular service post method: getUserDetails(username , password) { alert(password); return this.http.post<myData>("http://localhost/test/api/auth.php", { username, password }); } This is the structure of my PHP file: <?php ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...