Not able to load images from external resource conditionally


#1

I have a condition in which i am showing the thumbnail conditionally like:

<img ng-src="{{story.thumbnail}}" ng-if="story.thumbnail.startsWith('http')">

So, If the src starts with ‘http’ then only i need to show the thumbnail otherwise i don’t want to show it.
It works totally fine when testing in browser with or without ng-if but in android device it works only if i remove ng-if. When i apply ng-if and test in android device it doesn’t show the image for the satisfied condition. Any kind of help will be appreciated.

Thanks in advance.


#2

Have you tried using ng-show ? Does it works?


#3

I tried ng-show as well but no luck


#4

try
ng-if="{{story.thumbnail.startsWith(‘http’)}}“
or
ng-show=”{{story.thumbnail.startsWith(‘http’)}}"

(how does one embed full html snippets?)


#5

In an appropiate place do have your script do something like this…(adjust for your code!!!)

.controller('ImageCtrl', function ($scope) {
    $scope.URL = "http://sourcefed.com/wp-content/uploads/2012/10/twitter-for-ios-app-thumbnail.jpg";
 
    $scope.ShowIt = function () {
        return $scope.URL.startsWith('http');
    };

… and in your html do this…(I tried it this way and it worked)

<div ng-show="ShowIt()">
<img ng-src="{{URL}}">
</div>

replace “URL” with your appropriate code.


#6

UPDATE

The previous post didn’t work after all…

But this did…

You MUST USE this ES3-compatible polyfill …(that’s the only way I got it to fully work)
here is link startswith polyfill

just copy the startswith.js file, and include reference script in your html

<script src="startswith.js"></script>

then use “startsWith” as normal…
as in

<div ng-show="URL.startsWith('http')">
<img ng-src="{{URL}}">
</div>

I tested true and false cases and it worked this time, before I only tested for true case and didn’t check the false case…in the false case the image still showed! But in this version it works for true and false cases…

ps. DON’T FORGET TO ADJUST HTML FOR YOUR CODE


#7

Here is full source if you want to test with it…
Start with ionic project with blank template
replace index.html with this html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
 
    <style>
        .angular-google-map-container {
            width: 100%;
            height: 504px;
        }
    </style>
 
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <script src="lib/ionic/js/ionic.bundle.js"></script>
 
    <link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
 
    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->
 
    <script>
        /*! https://mths.be/startswith v0.2.0 by @mathias */
        if (!String.prototype.startsWith) {
            (function () {
                'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
                var defineProperty = (function () {
                    // IE 8 only supports `Object.defineProperty` on DOM elements
                    try {
                        var object = {};
                        var $defineProperty = Object.defineProperty;
                        var result = $defineProperty(object, object, object) && $defineProperty;
                    } catch (error) { }
                    return result;
                }());
                var toString = {}.toString;
                var startsWith = function (search) {
                    if (this == null) {
                        throw TypeError();
                    }
                    var string = String(this);
                    if (search && toString.call(search) == '[object RegExp]') {
                        throw TypeError();
                    }
                    var stringLength = string.length;
                    var searchString = String(search);
                    var searchLength = searchString.length;
                    var position = arguments.length > 1 ? arguments[1] : undefined;
                    // `ToInteger`
                    var pos = position ? Number(position) : 0;
                    if (pos != pos) { // better `isNaN`
                        pos = 0;
                    }
                    var start = Math.min(Math.max(pos, 0), stringLength);
                    // Avoid the `indexOf` call if no match is possible
                    if (searchLength + start > stringLength) {
                        return false;
                    }
                    var index = -1;
                    while (++index < searchLength) {
                        if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
                            return false;
                        }
                    }
                    return true;
                };
                if (defineProperty) {
                    defineProperty(String.prototype, 'startsWith', {
                        'value': startsWith,
                        'configurable': true,
                        'writable': true
                    });
                } else {
                    String.prototype.startsWith = startsWith;
                }
            }());
        }
 
        // Ionic Starter App
 
        // angular.module is a global place for creating, registering and retrieving Angular modules
        // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
        // the 2nd parameter is an array of 'requires'
        // 'starter.services' is found in services.js
        // 'starter.controllers' is found in controllers.js
        angular.module('app', ['ionic'])
 
        .run(function ($ionicPlatform) {
            $ionicPlatform.ready(function () {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                if (window.cordova && window.cordova.plugins.Keyboard) {
                    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                }
                if (window.StatusBar) {
                    // org.apache.cordova.statusbar required
                    StatusBar.styleDefault();
                }
            });
        })
 
        .config(function ($stateProvider, $urlRouterProvider) {
 
            // Ionic uses AngularUI Router which uses the concept of states
            // Learn more here: https://github.com/angular-ui/ui-router
            // Set up the various states which the app can be in.
            // Each state's controller can be found in controllers.js
            $stateProvider
 
              .state('page1', {
                  url: '',
                  templateUrl: 'page1.html'
              })
            ;
 
            // if none of the above states are matched, use this as the fallback
 
            $urlRouterProvider.otherwise('');
 
        })
 
        .controller('ImageCtrl', function ($scope) {
            $scope.MyURL = "http://sourcefed.com/wp-content/uploads/2012/10/twitter-for-ios-app-thumbnail.jpg";
            $scope.URL = "http://sourcefed.com/wp-content/uploads/2012/10/twitter-for-ios-app-thumbnail.jpg";
 
            $scope.ShowIt = function () {
                if ($scope.URL.startsWith('http') == true)
                    return true;
                return false;
            };
 
        });
    </script>
</head>
<body ng-app="app" animation="slide-left-right-ios7">
    <div style="">
        <div style="">
            <ion-nav-bar class="bar-stable">
            <ion-nav-back-button class="button-icon icon ion-ios7-arrow-back">Back</ion-nav-back-button>
        </ion-nav-bar>
            <ion-nav-view></ion-nav-view>
        </div>
    </div>
    <script id="page1.html" type="text/ng-template">
 
<ion-view style="" title="Page" ng-controller="ImageCtrl">
    <ion-content class="has-header" padding="true">
    <div ng-show="URL.startsWith('http')">
    <img ng-src="{{URL}}">
    </div>
    <p>URL = {{URL}}</p>
    <p>URL.startsWith('http')= {{URL.startsWith('http')}}</p>
    <div>
    <button class="button button-positive" ng-click="URL=MyURL">http url</button>
    <button class="button button-positive" ng-click="URL='x'">non http url</button>
    </div>
    </ion-content>
</ion-view></script>
</body>
</html>

this is when url starts with “html”

this is when url does not starts with “html”


#8

ps. I embeded poly into html, you should have it in a separate js file.


#9

Thanks Martin. It worked for me :smile: