0

I'd like to do an $http get request and return the result to the front-end. On the front-end, I use {{ 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
        }))
    }
}])

The result is on the front-end I just get {} (looks like an empty object). But my console log shows the desired HTML.

I'm pretty sure the general set-up is right because if I just do return "it works" in there, that works. I think the problem is something about JS scoping, returns or $http that I'm not getting.

2
  • 1
    possible duplicate of Asynchronously initialize AngularJS filter Commented Feb 16, 2015 at 9:37
  • @ShayFriedman Can you explain why you think this is a duplicate? Commented Feb 16, 2015 at 15:04

1 Answer 1

1

Noah,

The expression is being resolved to {} because the object you are returning in the filter definition is empty in fact. You are returning a promise and AngularJS is just printing the returned object in your HTML - not the resolved value as you probably expect.

You are using AngularJS filters in an inappropriate way in this case. In order to get the functionality you want, you should create a directive instead. You could use the directive in the following way in your HTML:

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

And implement it with the following 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);
                });
            }
    };
}]);

Valeu!

Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't it be <iframely url="{{ URL-STRING }}"></iframely> or something. How does the URL get piped in?
Yes. You can substitute /content/data.html by {{variable}}.
I've submitted an edit for your post that makes that work. Will mark correct when edit is accepted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.