AngularJS interpolation error when parsing Object - angularjs

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

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.

Related

Assign C# MVC View variables to AngularJS

I am getting object not set to instance during page load inside angularJs code
View
#model IAAS_Application.Models.ManageModels
#{
ViewBag.Title = "IAAS";
Layout = null;
}
My Angular Module
var app = angular.module('R1_myApp', []);
app.controller('R1_myCtrl', function ($scope, $http, $window, $compile) {
$scope.initEditModeData=function(){
debugger;
if(1==0){
$scope.PP.Private =(#Model.PP==null)?false:#Model.PP.Private;
$scope.PP.Public = (#Model.PP==null)?false:#Model.PP.Public;
$scope.PP.Cust_Name= (#Model.PP==null)?"":#Model.PP.Cust_Name;
$scope.PP.Cust_Flag=false
}
};
});
I am getting this error
I have put Null condition to make sure it doesn't enter inside. But by default while page load, control enters in and gives error.
What am I missing? can anyone help me?
I tried inititializing the object in c# MVC code and then send it it view. It worked. I am not getting error now.
obj.PP = new PP();
Return view(obj)

Why is my sanitized img tags coming up empty?

The following code is a function that uses parameters. When I alert the variable, the string appears exactly how it is supposed to.
$scope.createMap = function(size,scale,center,zoom,style){
$scope.myMap = "<img ng-src='https://maps.googleapis.com/maps/api/staticmap?size="+size+"&scale="+scale+"&center=IL"+center+"&style="+style+"&zoom="+zoom+"'>";
alert($scope.myMap);
return;
}
However, on the HTML page where this is binded to:
<div ng-bind-html="myMap" id="myStaticMap">
MAP GOES HERE
</div>
The area is empty and when I "inspect element" there is <img></img>, so it is registering it is an image, but coming up empty.
Same thing happens here:
$scope.displayPage = function(page){
$scope.siteName = $scope.names[page].PageName;
$scope.logo = "<img ng-src='"+$scope.names[page].logo+"'>";
alert($scope.logo);
$scope.createMap($scope.names[page].Size,$scope.names[page].Scale,$scope.names[page].Center,$scope.names[page].Zoom,$scope.names[page].Style);}
Where the parameter is being used a little bit differently. But again, the alert for $scope.logo is alerting the correct string but there is <img></img> where it is supposed to be binded. $scope.siteName is binded fine, but then, it is not binding any HTML.
I am using the sanitize module:
var app = angular.module('myApp', ["ngSanitize"]);
(the script is placed last in my list of external references)
So I am not sure what is wrong here.
UPDATE: So I did the suggestion in answer below and it is working when I change ng-src to src so that is awesome. However, I am getting the error below in my web console, anyone know why? I get it whether I use ng-src or src:
"Error: html.indexOf is not a function
htmlParser#http://code.angularjs.org/1.0.3/angular-sanitize.js:205:12
$sanitize#http://code.angularjs.org/1.0.3/angular-sanitize.js:119:1
ngBindHtmlWatchAction#http://code.angularjs.org/1.0.3/angular-sanitize.js:420:1
Yd/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:110:371
Yd/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:360
m#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:72:452
w#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:77:463
ye/https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:79:24
var app = angular.module('myApp', ["ngSanitize"]);
app.controller('customersCtrl', function($scope, $http, $sce) {
When you parse html from within your controller, you have to use the $sce dependency from angular, in order to mark the html as "trusted":
angular.module("yourModule").controller("yourController",
["$scope", "$sce", function ($scope, $sce) {
$scope.displayPage = function(page){
$scope.siteName = $scope.names[page].PageName;
$scope.logo = $sce.trustAsHtml("<img ng-src='"+$scope.names[page].logo+"'>");
alert($scope.logo);
$scope.createMap($scope.names[page].Size,$scope.names[page].Scale,$scope.names[page].Center,$scope.names[page].Zoom,$scope.names[page].Style);}
}
]);

Use a custom function from an angular template

I'm displaying urls from an angular template, but I'd like to 'slugify' it, that is, replace those ugly chars. Right now I just want to replace spaces with '_'.
This is the code I have on my index.html file
<a ng-href="#/{{url}}">{{name}}</a>
I'd like to define a slugify function like this:
slugify = function(url) {
return url.replace(' ', '_');
};
And then being able to call it from every the template like this
<a ng-href="#/{{slugify(url)}}">{{name}}</a>
How could I achieve it?
-- edit
I finally went with #underscore solution (added it to the $rootScope) and from a normal controller it works ok. But from a template inside the ng-app directive, but with no ng-controller, it works too, but it gives me the following error, lots of times:
Error: error:interr
Interpolation Error
Can't interpolate: #/{{slug(b.link)}}
TypeError: undefined is not a function
This is the offending code:
<a ng-show='b.link' ng-href="#/{{slug(b.link)}}">{{b.name}}</a>
I tried with regular href and ng-href, and also with $root.slug, but it always throws the same error a dozen times, nevertheless it works ok.
Also tried defining a filter, like Peter said, and it gave me the same error:
Can't interpolate: #/{{b.link | slug}}
TypeError: undefined is not a function
Nevertheless, it worked ok too...
--
ok, final edit
It seems when angular is bootstraping the input value might be undefined (as explained here: https://stackoverflow.com/a/18573426/47633)
I could solve the nasty error message with:
presuApp.filter('slug', function() {
return function(input) {
return input ? input.replace(/ /g, '_') : '';
}
});
Create a function in your controller e.g.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.theInput = 'example input';
$scope.slugify = function(input) {
input = input.replace(' ', '_');
return input;
}
});
Here's a plunkr:
http://plnkr.co/edit/RARhGQzQoGPtWhoFColL?p=preview
A more correct way might be to use a filter:
app.filter('slugify', function() {
return function(input) {
input = input.replace(' ', '_');
return input
}
})
And in the template you put:
using a filter:
{{ theInput | slugify }}
Also added that to plunkr
"And then being able to call it from every the template like this"
In this case you should use $rootScope instead of controller scope.
just use it in the $rootScope
$rootScope.slugify = function(url) {
return url.replace(' ', '_');
};
Define it in the app.run(); . So the function will define when angular bootstrap
In your controller you can bind $scope to a function to make it accessible via the html.
$scope.slugify = function(url) {
return url.replace(' ', '_');
};

Using $translate in a controller

I'm trying to get the text defined in our translations.js file in order to pass it to an angular-bootstrap alert as its text. I've injected the $translate service into the controller and am using the $translate service like so:
$translate('TXT_ALERT_MSG').then(function (translation) {
$log.debug( translation );
});
but it breakes angular and states the following error message:
TypeError: object is not a function
This is thrown on the very first line of the code above. I wrapped it in a promise to make sure i only print the value upon successfully retrieving the translation. I also tried assigning the value to a variable but this throws the same error:
function getTranslation() {
var msg = $translate('TXT_ALERT_MSG');
$log.debug(msg);
}
getTranslation();
This is most likely something simple so what is it?
Thanks
EDIT
How I inject the translate module into the app:
angular.module('MainApp',['pascalprecht.translate']);
and how it's configured:
angular.module('MainApp').config(['$translateProvider', 'ConfigProvider', function ($translateProvider, ConfigProvider) {
var config = ConfigProvider.$get();
var rootUrl = config.get('ourRootUrl');
$translateProvider.translations('en', {
// all our translations e.g.
TIMED_OUT_BUTTON: 'Return to Dashboard'
$translateProvider.preferredLanguage('en');
}]);
Try to get the translations by translate filter
$filter('translate')('TIMED_OUT_BUTTON')

AngularJS : Error: registerService.getRegisterResponse is not a function

Error: registerService.getRegisterResponse is not a function
I getting Above Error on console of the web browser. While Accessing the a method(i.e saveRegisterResponse()) from Controller (i.e RegistrationCtrl) as registerService.getRegisterResponse() Method in registerService.
Here it is clear cut code.... For Both registerCtrl(controller) & regiterService(Service)...
Am placed both Service and Controller in app.js
**registerCtrl(Controller).**
var app=angular.module("app.chart.ctrls",['ngSanitize']);
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,registerService){
registerService.getRegisterResponse();
}]);
**registerService(Service)**
app.factory('registerService', function () {
var registerResponse = {};
return {
getRegisterResponse:function () {
return "xyz";
}
};
});
While Controller is loading am getting the Error
Angularjs Error: registerService.getRegisterResponse is not a function
How to Resolve it ? Thanks in Advance ...:)
It looks like you did not add logger as one of your controller's function arguments, which makes angular look for getRegisterResponse in your logger. Change your code to something like:
app.controller("registrationCtrl",
["$scope","$location","logger","registerService",function($scope,$location,logger, registerService){
registerService.getRegisterResponse();
}]);

Resources