EzDevInfo.com

angular-ui-router interview questions

Top angular-ui-router frequently asked interview questions

force view to reload in ionic framework

I am new to mobile application development with ionic and wanted to know

I have a scenario where the login / logout buttons are located in the menu and a simple

On login and logout I need reload the page, inorder to refresh the data, however

$state.go('mainPage') takes the user back to the view without reload. the controller behind it is never invoked.

Is there a way to do clear history and reload the state in ionic ?


Source: (StackOverflow)

How do I get the Back Button to work with an AngularJS ui-router state machine?

I have implemented an angularjs single page application using ui-router.

Originally I identified each state using a distinct url however this made for unfriendly, GUID packed urls.

So I have now defined my site as a much simpler state-machine. The states are not identified by urls but are simply transitioned to as required, like this:

Define Nested States

angular
.module 'app', ['ui.router']
.config ($stateProvider) ->
    $stateProvider
    .state 'main', 
        templateUrl: 'main.html'
        controller: 'mainCtrl'
        params: ['locationId']

    .state 'folder', 
        templateUrl: 'folder.html'
        parent: 'main'
        controller: 'folderCtrl'
        resolve:
            folder:(apiService) -> apiService.get '#base/folder/#locationId'

Transition to a Defined State

#The ui-sref attrib transitions to the 'folder' state

a(ui-sref="folder({locationId:'{{folder.Id}}'})")
    | {{ folder.Name }}

This system works very well and I love its clean syntax. However, as I am not using urls the back button does not work.

How do I keep my neat ui-router state-machine but enable the back button functionality?


Source: (StackOverflow)

Advertisements

Set URL query parameters without state change using Angular ui-router

How should I update the address bar URL with a changing query parameter using AngularJS' ui-router to maintain state when refreshing the page?

Currently, I am using $state.transitionTo('search', {q: 'updated search term'}) whenever input changes, but the problem is that this reloads the controller, redraws the window and loses any text input focus.

Is there a way to update stateParams and sync it to the window URL?


Source: (StackOverflow)

What is the difference between $routeProvider and $stateProvider in AngularJs

Please explain the difference between $routeProvider and $stateProvider in AngularJs.

Which is best practice.


Source: (StackOverflow)

Angular ui-router - how to access parameters in nested, named view, passed from the parent template?

Hi I am trying to access a parameter in the controller "ViewWorklogCrtl" while using ui-router and running into difficulty.

Basically, my parent template contains:

a(ui-sref="instance-ticket.worklog({id:{{ticket.testnum}}})") show

and then further down the page:

section(ui-view="top-section")

Then in my app.js, containing client-side routing info in short I have:

 $stateProvider
.state('instance-ticket', {
  url: '/ticket/:instanceID',
  templateUrl: 'partials/instance-ticket',
  controller: 'ViewTicketCrtl'
})
.state('instance-ticket.worklog', {
  views:{
    'top-section':{
      templateUrl:'/partials/ticket.worklog.jade',
      controller: 'ViewWorklogCrtl'
      }
  }
  })

The template loading is working correctly, the issue and question I can't find an answer to is - how to access "testnum" being passed through the ui-sref link, to and within the ViewWorkLogCtrl... Is there a better approach to this?

Much thanks!!!


Source: (StackOverflow)

Injecting $scope into an angular service function()

I have a Service:

angular.module('cfd')
  .service('StudentService', [ '$http',
    function ($http) {
    // get some data via the $http
    var path = 'data/people/students.json';
    var students = $http.get(path).then(function (resp) {
      return resp.data;
    });     
    //save method create a new student if not already exists
    //else update the existing object
    this.save = function (student) {
      if (student.id == null) {
        //if this is new student, add it in students array
        $scope.students.push(student);
      } else {
        //for existing student, find this student using id
        //and update it.
        for (i in students) {
          if (students[i].id == student.id) {
            students[i] = student;
          }
        }
      }
    };

But when I call save(), I don't have access to the $scope, and get ReferenceError: $scope is not defined. So the logical step (for me), is to provide save() with the $scope, and thus I must also provide/inject it to the service. So if I do that like so:

  .service('StudentService', [ '$http', '$scope',
                      function ($http, $scope) {

I get the following error: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- StudentService

The link in the error (wow that is neat!) lets me know it is injector related, and might have to do with order of declaration of the js files. I have tried reordering them in the index.html, but I think it is something more simple, such as the way I am injecting them.

Using Angular-UI and Angular-UI-Router


Source: (StackOverflow)

What is the Angular ui-router lifecycle? (for debugging silent errors)

The best I've found is http://www.ng-newsletter.com/posts/angular-ui-router.html. It doesn't go as deep as, for example, the order in which $stateChangeStart, exampleState.onEnter, exampleState.resolve, and exampleState.templateProvider fire.

A great answer format would be clean. Something like:

  1. Initial pageload of state foo:

    1. Angular lifecycle step 1
    2. UI router lifecycle step 1
    3. UI router lifecycle resolves occur
    4. UI router lifecycle onEnter fires
    5. Angular lifecycle step 2
  2. State change foo -> bar

    1. $stateChangeStart event fires
    2. foo onExit fires
    3. bar onEnter Fires
    4. templateUrl gets the template
    5. UI router plugs back into the Angular lifecycle in the digest loop (or wherever).
  3. Nested states

  4. Multiple named views:

  5. ui-sref clicked

Etc... Thanks!

EDIT: Debugging functions provided enough insight to meet the need. See my answer below for a snippet.


Source: (StackOverflow)

(Angular-ui-router) Show loading animation during resolve process

This is a two part question:

  1. I am using the resolve property inside $stateProvider.state() to grab certain server data before loading the controller. How would I go about getting a loading animation to show during this process?

  2. I have child states that also utilise the resolve property. The problem is that ui-router seems to want to finalise all resolves before loading any controller. Is there any way I can get the parent controllers to load once their resolves have been resolved, without having to wait for all the child resolves? An answer to this will likely also solve the first problem.


Source: (StackOverflow)

AngularJS UI Router - change url without reloading state

Currently our project is using default $routeProvider, and I am using this "hack", to change url without reloading page:

services.service('$locationEx', ['$location', '$route', '$rootScope', function($location, $route, $rootScope) {
    $location.skipReload = function () {
        var lastRoute = $route.current;
        var un = $rootScope.$on('$locationChangeSuccess', function () {
            $route.current = lastRoute;
            un();
        });
        return $location;
    };
    return $location;
}]);

and in controller

$locationEx.skipReload().path("/category/" + $scope.model.id).replace();

I am thinking of replacing routeProvider with ui-router for nesting routes, but cant find this in ui-router.

Is it possible - do the same with angular-ui-router?

Why do I need this? Let me explain with an example :
Route for creating new category is /category/new after clicking on SAVE I show success-alert and I want to change route /category/new to /caterogy/23 (23 - is id of new item stored in db)


Source: (StackOverflow)

What's the proper way to set a Router & RouterLink in Angular2 Dart

Question: What's the proper way to set a Router & RouterLink in Angular2 Dart

Here's my main.dart file:

import 'package:angular2/angular2.dart';
import 'package:angular2/router.dart';

import 'package:angular2/src/reflection/reflection.dart' show reflector;
import 'package:angular2/src/reflection/reflection_capabilities.dart' show ReflectionCapabilities;


@Component(
    selector: 'home'
)
@View(
    template: '<h1>I am Home</h1><a router-link="child">Go Child</a>',
    directives: const [RouterOutlet, RouterLink]
)
class Home {}

//
//
//

@Component(
  selector: 'child'
)
@View(
    template: '<h1>I am Child</h1><a router-link="home">Go Home</a>',
    directives: const [RouterOutlet, RouterLink]
)
class Child {}

//
//
//

@Component(
  selector: 'index'
)
@View(
  template: '''
  <router-outlet></router-outlet>
            ''',
  directives: const [RouterOutlet, RouterLink]
)
class Index {
  Router router;

  Index(Router this.router) {
    router.config({ 'path': '/child', 'component': Child, 'alias': 'child'});
    router.config({ 'path': '/', 'component': Home, 'alias': 'home'});
  }

}

main() {
  reflector.reflectionCapabilities = new ReflectionCapabilities();
  bootstrap(Index, routerInjectables);
}

Here's my approach:

In router_link.dart I see newHref coming back as null

onAllChangesDone() {
    if (isPresent(this._route) && isPresent(this._params)) {
      var newHref = this._router.generate(this._route, this._params);
      this._href = newHref;
      // Keeping the link on the element to support contextual menu `copy link`

      // and other in-browser affordances.
      print('newHref');
      print(newHref);
      DOM.setAttribute(this._domEl, "href", newHref);
    }

This results in an error and kills the navigation request.

    String expected
STACKTRACE:
#0      BlinkElement.setAttribute_Callback_2 (dart:_blink:7565)
#1      BlinkElement.setAttribute_Callback_2_ (dart:_blink:7566)
#2      Element.setAttribute (dart:html:13673)
#3      BrowserDomAdapter.setAttribute (package:angular2/src/dom/browser_adapter.dart:258:25)
#4      RouterLink.onAllChangesDone (package:angular2/src/router/router_link.dart:66:23)

Source: (StackOverflow)

$state.go toParams not passed to $stateParams

I am using AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I want to pass the referrer state to another state so I use the toParams of $state.go like so:

$state.go('toState', {referer: $state.current.name});

According to the docs, this should populate the $stateParams on the toState controller, but it is undefined. What am I missing?

I've created a plunk to demonstrate:

http://plnkr.co/edit/ywEcG1


Source: (StackOverflow)

Difference between $state.transitionTo() and $state.go() in AngularJS

In AngularJS, I see sometimes we use $state.transitionTo() and sometimes we use $state.go(). Can anyone tell me how they differ and when one should be used over the other?


Source: (StackOverflow)

Angular ui-router scroll to top, not to ui-view

I've just upgraded to ui-router 0.2.8 from 0.2.0 and I've noticed that when the state changes, the scroll position jumps to the top of te child ui-view that is the subject of the new state.

This is fine but I have two problems with it:

1) I have 30px padding between the top of the page and the ui-view and I would like it to scroll to the top of the page, leaving a gap. At the moment it goes exactly to the top of the ui-view which looks ugly. To achieve this I guess I either need to know how to get it to scroll to the top of the div that the ui-view is in (not the browser viewport), or I need to find out how to override $uiViewScroll to scroll to the ui-view minus 30px.

I have tried $uiViewScrollProvider.useAnchorScroll(); but if I do that it doesn't scroll at all. I have also tried <ui-view autoscroll="false">;, which also stops the scrolling completely.

2) It doesn't actually scroll at the moment, just jumps. Is it suppose to scroll or is it up to the developer to do this with CSS transitions?

Any help would really be appreciated :)


Source: (StackOverflow)

`ui-router` $stateParams vs. $state.params

With ui-router, it's possible to inject either $state or $stateParams into a controller to get access to parameters in the URL. However, accessing parameters through $stateParams only exposes parameters belonging to the state managed by the controller that accesses it, and its parent states, while $state.params has all parameters, including those in any child states.

Given the following code, if we directly load the URL http://path/1/paramA/paramB, this is how it goes when the controllers load:

$stateProvider.state('a', {
     url: 'path/:id/:anotherParam/',
     controller: 'ACtrl',
  });

$stateProvider.state('a.b', {
     url: '/:yetAnotherParam',
     controller: 'ABCtrl',
  });

module.controller('ACtrl', function($stateParams, $state) {
   $state.params; // has id, anotherParam, and yetAnotherParam
   $stateParams;  // has id and anotherParam
}

module.controller('ABCtrl', function($stateParams, $state) {
   $state.params; // has id, anotherParam, and yetAnotherParam
   $stateParams;  // has id, anotherParam, and yetAnotherParam
}

The question is, why the difference? And are there best practices guidelines around when and why you should use, or avoid using either of them?


Source: (StackOverflow)

Angular ui router passing data between states without URL

I am facing this problem of passing data between two states without exposing the data in the url, it's like user cannot really directly land on this state.

For example. I have two states "A" and "B". I am doing some server call in state "A" and passing the response of the call to state "B". The response of the server call is a string message, which is quite long, so i cannot expose that in the url.

So is there any way in angular ui router to pass data between states, without using url params ?


Source: (StackOverflow)