HTML enhanced for web apps AngularJS — Superheroic JavaScript MVW Framework angularjs is what html would have been, had it been designed for building web-apps. declarative templates with data-binding, mvw, mvvm, mvc, dependency injection and great testability story all implemented with pure client-side javascript!

if else statement in AngularJS templates

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.

I want to make a condition like this:

if video.yt$aspectRatio equals widescreen then 
    element's attr height="270px"
    element's attr height="360px"

I'm iterating the videos using ng-repeat. Have no idea what should I do for this condition:

  • Add a function in the scope?
  • Do it in template?

Source: (StackOverflow)

Redirecting to a certain route based on condition

I'm writing a small AngularJS app that has a login view and a main view, configured like so:

 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
 .otherwise({redirectTo: '/login'});

My LoginController checks the user/pass combination and sets a property on the $rootScope reflecting this:

function LoginController($scope, $location, $rootScope) {
 $scope.attemptLogin = function() {
   if ( $scope.username == $scope.password ) { // test
        $rootScope.loggedUser = $scope.username;
        $location.path( "/main" );
    } else {
        $scope.loginError = "Invalid user/pass.";

Everything works, but if I access http://localhost/#/main I end up bypassing the login screen. I wanted to write something like "whenever the route changes, if $rootScope.loggedUser is null then redirect to /login"


... wait. Can I listen to route changes somehow? I'll post this question anyway and keep looking.

Source: (StackOverflow)


confused about service vs factory

As I understand it, when inside a factory I return a object that gets injected into a controller. When inside a service I am dealing with the object using this and not returning anything.

I was under the assumption that a service was always a singleton, and that a new factory object gets injected in every controller. However as it turns out, a factory object is a singleton too?

Example code to demonstrate:

var factories = angular.module('app.factories', []);
var app = angular.module('app',  ['ngResource', 'app.factories']);

factories.factory('User', function () {
  return {
    first: 'John',
    last: 'Doe'

app.controller('ACtrl', function($scope, User) {
  $scope.user = User;

app.controller('BCtrl', function($scope, User) {
  $scope.user = User;

When changing user.first in ACtrl it turns out that user.first in BCtrl is also changed, e.g. User is a singleton?

My assumption was that a new instance was injected in a controller with a factory?

Source: (StackOverflow)

Insert HTML into view using AngularJS

Is it possible to create an HTML fragment in an Angular controller and have this HTML shown in the view?

This comes from a requirement to turn an inconsistent JSON blob into a nested list of id : value pairs. Therefore the HTML is created in the controller and I am now looking to display it.

I have created a model property, but cannot render this in the view without it just printing the HTML.


It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.

Example controller :

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';

Example view :

<div ng:bind="customHtml"></div>

Gives :

    "<ul><li>render me please</li></ul>"

Source: (StackOverflow)

How to set the value property in AngularJS' ng-options?

Here is what seems to be bothering a lot of people (including me). When using the ng-options directive in AngluarJS to fill in the options for a <select> tag I cannot figure out how to set the value for an option. The documentation for this is really unclear - at least for a simpleton like me.

I can set the text for an option easily like so:

ng-options="select p.text for p in resultOptions"

when resultOptions is for example:

        "value": 1,
        "text": "1st"
        "value": 2,
        "text": "2nd"

Should be (and probably is) the most simple thing to set the option values, but so far I just don't get it.

Source: (StackOverflow)

Difference between angular-route and angular-ui-router

I am new to AngularJS. I find Angular quite interesting and planning to use angular in my big apps. So I am in the process to find out the right modules to use.

What is the difference between ngRoute (angular-route.js) and ui-router (angular-ui-router.js) modules?

In many articles when ngRoute is used, route is configured with $routeProvider. However, when used with ui-router, route is configured with $stateProvider and $urlRouterProvider.

This creates a bit of confusion for me. Which module should I use for better manageability and extensibility? Your answers are greatly appreciated.

Source: (StackOverflow)

How to set focus on input field?

What is the 'Angular way' to set focus on input field in AngularJS?

More specific requirements:

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal.
  2. Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

I tried to achieve the first requirement with autofocus, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).

Any help will be appreciated.

Source: (StackOverflow)

How do search engines deal with AngularJS applications?

I see two issues with AngularJS application regarding search engines and SEO:

1) What happens with custom tags? Do search engines ignore the whole content within those tags? i.e. suppose I have

  <h1>Hey, this title is important</h1>

would <h1> be indexed despite being inside custom tags?

2) Is there a way to avoid search engines of indexing {{}} binds literally? i.e.


I know I could do something like

<h2 ng-bind="title"></h2>

but what if I want to actually let the crawler "see" the title? Is server-side rendering the only solution?

Source: (StackOverflow)

Combating AngularJS executing controller twice

I understand AngularJS runs through some code twice, sometimes even more, like $watch events, constantly checking model states etc.

However my code:

function MyController($scope, User, local) {

var $scope.User = local.get(); // Get locally save user data

User.get({ id: $scope.User._id.$oid }, function(user) {
  $scope.User = new User(user);


Is executed twice, inserting 2 records into my DB. I'm clearly still learning as I've been banging my head against this for ages!

Source: (StackOverflow)

How to use a filter in a controller?

I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller?

This is what I've tried so far:

function myCtrl($scope,filter1)
    // i simply used the filter function name, it is not working.

Source: (StackOverflow)

Complex nesting of partials and templates

My question involves how to go about dealing with complex nesting of templates (also called partials) in an AngularJS application.

The best way to describe my situation is with an image I created:

AngularJS Page Diagram

As you can see this has the potential to be a fairly complex application with lots of nested models.

The application is single-page, so it loads an index.html that contains a div element in the DOM with the ng-view attribute.

For circle 1, You see that there is a Primary navigation that loads the appropriate templates into the ng-view. I'm doing this by passing $routeParams to the main app module. Here is an example of what's in my app:

angular.module('myApp', []).
    config(['$routeProvider', function($routeProvider) {
            when("/job/:jobId/zones/:zoneId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/zone_edit.html' }).
            when("/job/:jobId/initial_inspection", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/initial_inspection.html' }).
            when("/job/:jobId/zones/:zoneId/rooms/:roomId", { controller: JobDetailController, templateUrl: 'assets/job_list_app/templates/room_edit.html' })       


In circle 2, the template that is loaded into the ng-view has an additional sub-navigation. This sub-nav then needs to load templates into the area below it - but since ng-view is already being used, I'm not sure how to go about doing this.

I know that I can include additional templates within the 1st template, but these templates are all going to be pretty complex. I would like to keep all the templates separate in order to make the application easier to update and not have a dependency on the parent template having to be loaded in order to access its children.

In circle 3, you can see things get even more complex. There is the potential that the sub-navigation templates will have a 2nd sub-navigation that will need to load its own templates as well into the area in circle 4

How does one go about structuring an AngularJS app to deal with such complex nesting of templates while keeping them all separate from one another?

Source: (StackOverflow)

How can I post data as form data instead of a request payload?

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a "Request Payload" (as described in the Chrome debugger network tab). The jQuery $.ajax method does the same call, but submits xsrf as "Form Data".

How can I make AngularJS submit xsrf as form data instead of a request payload?

var url = 'http://somewhere.com/';
var xsrf = {fkey: 'xsrf key'};

    method: 'POST',
    url: url,
    data: xsrf
}).success(function () {});

    type: 'POST',
    url: url,
    data: xsrf,
    dataType: 'json',
    success: function() {}

Source: (StackOverflow)

Does it make sense to use Require.js with Angular.js? [closed]

I'm a newbie to Angular.js and trying to understand how it's different from Backbone.js... We used to manage our packages dependencies with Require.js while using Backbone. Does it make sense to do the same with Angular.js?

Source: (StackOverflow)

What is the difference between Polymer elements and AngularJS directives?

On the Polymer Getting Started page, we see an example of Polymer in action:

    <!-- 1. Shim missing platform features -->
    <script src="polymer-all/platform/platform.js"></script>
    <!-- 2. Load a component -->
    <link rel="import" rel='nofollow' href="x-foo.html">
    <!-- 3. Declare the component by its tag. -->

What you will notice is <x-foo></x-foo> being defined by platform.js and x-foo.html.

It seems like this is the equivalent to a directive module in AngularJS:

angular.module('xfoo', [])
.controller('X-Foo', ['$scope',function($scope) {
    $scope.text = 'hey hey!';
.directive('x-foo', function() {
    return {
        restrict: 'EA',
        replace: true,
        controller: 'X-Foo',
        templateUrl: '/views/x-foo.html',
        link: function(scope, controller) {
  • What is the difference between the two?

  • What problems does Polymer solve that AngularJS has not or will not?

  • Are there plans to tie Polymer in with AngularJS in the future?

Source: (StackOverflow)

What is the difference between '@' and '=' in directive scope

I've read the AngularJS documentation on the topic carefully, and then fiddled around with a directive. Here's the fiddle.

And here are some relevant snippets:

  • from the html:

    <pane bi-title="title" title="{{title}}">{{text}}</pane>
  • from the pane directive:

    scope: { biTitle: '=', title: '@', bar: '=' },

There are several things I don't get:

  • why do I have to use "{{title}}" with '@' and "title" with '='?
  • can I also access the parent scope directly, without decorating my element with an attribute?
  • The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

I found another fiddle that shows the expression solution too: http://jsfiddle.net/maxisam/QrCXh/

Source: (StackOverflow)