Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS interpolation error when parsing Object

Just starting out with AngularJS. Trying to build a single page app to display slides/pages of my comic, one at a time.

The data is getting pulled in from a JSON file, and that's working correctly. But Angular is throwing errors when I try to set up some basic binding. Any thoughts..?

HTML

<span ng-bind-html="showCurrentTitle"></span>

JS

var comicsApp = angular.module('comicsApp', ['ngSanitize']);

comicsApp.controller('comicsCtrl', ['$scope', '$http',
  function comicsCtrl($scope, $http) {
    $http.get('/luv-slimline/test/comics.json').success(function(data) {
      $scope.comics = data.comics;
    });

    $scope.showCurrentTitle = function() {
    return $scope.comics[0].title;
}
} //end ComicsCtrl
]);

Error

TypeError: Object function () { return $scope.comics[0].title; } has no method 'indexOf'

If I strip out the ngSanitize module, then the error message changes.

Alt error

Error: [$sce:unsafe] http://errors.angularjs.org/undefined/$sce/unsafe

And if I swap out the ng-bind-html directive for the older-style mustache braces, then the error message changes again.

Alt error (2)

Error: [$interpolate:interr] http://errors.angularjs.org/undefined/$interpolate/interr?p0=%7B%7BshowCurr…()%7D%7D&p1=TypeError%3A%20Cannot%20read%20property%20'0'%20of%20undefined

Help, please?

Cheers, Dan

like image 775
Dan Avatar asked Dec 19 '25 16:12

Dan


1 Answers

I'm not familiar with the errors you are receiving, or ng-sanitize or the ng-bind-html tag. However, your javascript code looks problematic to me.

var comicsApp = angular.module('comicsApp', ['ngSanitize']);

    comicsApp.controller('comicsCtrl', ['$scope', '$http',
      function comicsCtrl($scope, $http) {

       //so this runs immediately, but . . .
       $http.get('/luv-slimline/test/comics.json').success(function(data) {
          // . . . this is going to happen async, so this value won't be set 
          //before the initial binding occurs
          $scope.comics = data.comics;
        });
    $scope.showCurrentTitle = function() {
    // . . . as a result, comics will be undefined initially.
    return $scope.comics[0].title;
}
} //end ComicsCtrl
]);

I think you need to define an initial value for $scope.comics before your http.get. Something like:

$scope.comics = [];
$scope.comics.push({title: "testTitle"});

Edit

Based on your comment, if you are now just binding to showCurrentTitle (which I would rename to currentTitle, as it makes more sense), you shouldn't even need to initialize $scope.comics--it should work without that code.

like image 85
Phil Sandler Avatar answered Dec 22 '25 06:12

Phil Sandler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!