Understanding how scope variables work in Angular UI Router

In the course of developing an AngularJS app, I have encountered an issue with accessing scope variables from the View. Here is a snippet of my code:

Route

.state('dashboard.unique', {
            url:'/unique/:id',
            resolve: {
              auth: function resolveAuthentication(AuthResolver) {
                return AuthResolver.resolve();
              }
            },
            views: {
              'menuContent': {
                templateUrl: 'closerViews/dashboard/uniqueservice.html',
                controller: 'uniqueController'
              }
            }
        });

View:

<ion-view title="Closer" class="closerTitle">
  <ion-nav-buttons side="left">
    <button menu-toggle="left" class="button button-icon icon ion-drag"></button>
  </ion-nav-buttons>
  <ion-content class="has-header insideAPP lightBG" id="servicio_unico">
    <div class='gallery'>
      <img ng-src="{{urlImagen}}" />
    <h1>{{nombre}}</h1>
    <p>{{descripcion}}</p>
    <ul>
      <li>Price: {{precio | currency}}</li>
      <li>Duration: {{duracion}}</li>
      <li>Start Time: {{hora_inicio}}</li>
      <li>Rating: </li>
    </ul>
  </ion-content>
</ion-view>

Controller

app.controller('uniqueController', function($scope, $stateParams, $ionicLoading, $http, CLOSER_SERVER) {
    $scope.urlImagen = "img/no_image.png";
    $scope.nombre = "Service Name";
    $scope.descripcion = "Service Description";
    $scope.precio = "999 €";
    $scope.hora_inicio = "Service Time";
    $scope.duracion = "Service Duration";
    $scope.id_servicio = $stateParams.id;

    var urlMaker = CLOSER_SERVER.url+'/service/'+$scope.id_servicio;
    $http.get(urlMaker)
      .success(function(response) {
        var data = JSON.stringify(response);
        data = JSON.parse(data);
        console.log(data);
        $scope.urlImagen = data.urlImagen;
        $scope.nombre = data.nombre;
        $scope.descripcion = data.descripcion;
        $scope.id_service = data.id_service;
        $scope.precio = data.precio;
        $scope.hora_inicio = data.hora_inicio;
        $scope.duracion = data.duracion;
        //Digest the data to propagate it throughout the model

      })
      .error(function(error, data, headers){
        console.log("Connection error");
      });
});

No matter what I try, the view remains empty. I am utilizing Angular UI Router and wondering if there's a misunderstanding in how scopes are used with ui router?

EDIT Routes.js

closer.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('home', {
            url:'/',
            templateUrl: 'closerViews/init.html',
            controller: 'initController'
        })
        .state('login', {
            url:'/login',
            templateUrl: 'closerViews/login.html',
            //We will include a resolve to ReconnectResolver here, to check if
            //the token is stored and provide us with a renewed token
            controller: 'loginController'
        })
        ... (more states defined here)
        .state('dashboard.allservices', {
            url:'/allservices',
            resolve: {
              auth: function resolveAuthentication(AuthResolver) {
                return AuthResolver.resolve();
              }
            },
            views: {
              'menuContent': {
                templateUrl: 'closerViews/dashboard/allservices.html',
                controller: 'servicesController'
              }
            }
        })
        .state('dashboard.unique', {
            url:'/unique/:id',
            resolve: {
              auth: function resolveAuthentication(AuthResolver) {
                return AuthResolver.resolve();
              }
            },
            views: {
              'menuContent': {
                templateUrl: 'closerViews/dashboard/uniqueservice.html',
                controller: 'uniqueController'
              }
            }
        });
        $urlRouterProvider.otherwise('/');

}]);

Answer №1

When utilizing an alias for a view, remember to specify the Angular directive where your template will be rendered:

<div ui-view="menuContent">
. Additionally, ensure that you have specified a controller for the URL '/unique/:id'. This can be done either in the configuration or within the HTML using the 'ng-controller' attribute.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the ideal method for creating multi-view layouts in ASP.NET MVC?

I've been pondering the best approach to create multi-view layouts using ASP.NET MVC. For instance, in angular-based SPAs, loading different views into a layout is quite simple: <div ui-view="header"></div> <div ui-view="content">& ...

AngularJS ngResource event deletion

Trying to maintain an updated list of resources while a user interacts with it. Utilizing AngularJS ngResource, the initial list is retrieved using the query method. Each resource should have a $remove (or $delete) method available, correct? However, upon ...

How can I independently use the draggable and click features in KineticJS?

How can I implement both draggable and click functionalities on the same node in KineticJS? Currently, when I make an element draggable, a click event is also triggered after the drag. You can view the example in JSFiddle at http://jsfiddle.net/matobaa/LZ ...

Experience an engaging and dynamic liquid metal orb using Three.js

As I dive into the world of JavaScript and experiment with Three.js, I came across a fascinating tutorial by Paul Lewis. He demonstrated how to create an interactive liquid metal ball with Three.js, similar to the one showcased at In an attempt to incorpo ...

The Google Chart is failing to show up on the screen

I'm having trouble implementing a feature that involves selecting a region from a dropdown list and requesting rainfall data to display in a Google Chart. Unfortunately, I've encountered some issues with it. Could you please help me identify ...

bash: The command "nodemon" could not be located

My experience with nodemon has been smooth for the past few months. However, today I encountered an error that I couldn't resolve. Despite uninstalling and reinstalling nodemon, as well as force installing it, I still received the same error message w ...

The Django project does not contain any JS script

Currently expanding my knowledge in Django and encountering an issue. The JS script is not being included in the Django project despite having the correct path. While the page itself with the graph block functions properly, the output of a round or bar cha ...

Maintain consistent sorting of checked items at the top in jqGrid multi-select mode

My jqGrid displays a list of rows, totaling several thousand. Upon loading the grid, all data is retrieved with previously selected items already checked. I am wondering, is there a way to set the sort order to consistently display the selected items at ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

Using NPM ES Module packages with Express and Babel can be problematic

If you want to easily try out the code, it's all available in this GitHub repository. You can also find the package published on npm for testing purposes. I am currently attempting to get a simple NPM ESModule package to work with Node.js CommonJS + ...

An asynchronized code block processes an array of multiple Ajax deferred calls, concluding with a synchronous final code block

I am new to the world of jQuery and AJAX and I'm currently exploring how deferrals and promises can help me solve a particular issue. Here's what I'm trying to achieve: I want to make calls to multiple URLs, process the returned results in p ...

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Using Javascript to deactivate a clickable image upon clicking another image

I have two buttons with alert functions assigned to each. I want the function on the first button to only work when that button is clicked, and not work if the second button has been clicked. Below is the code I've tried, but it's not functioning ...

Why is the Javascript Ecommerce add to cart feature failing to work properly?

I've been working on implementing an add to cart feature using a combination of Javascript and Django, with the main functionality relying on Javascript. Here's the snippet of code I have for cart.js: var updateBtns = document.getElementsByClass ...

Retrieving data from a simulated angular service and making calls accordingly

I'm struggling with writing tests for a controller method that relies on an Angular service call and needs to test the code inside the .then() function afterwards. Here's the basic concept: // Controller $scope.myMethod = function() { meth ...

The foundation of JSON and its structural encoding

Looking to deserialize JSON from Java, here's how it's done: Java jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO); JSON "accounts" : [ { "name" : "1009427721", "value" : 16850.79, "children" : ...

What is the equivalent of {...props} in React for destructuring props in Vue?

When working in React, I can destructure props with ease: function MyComponent() { const myProp = { cx: '50%', cy: '50%', r: '45%', 'stroke-width': '10%' } return ( <svg> ...

Is there a way to seamlessly update a field without refreshing the page or overloading the server?

I'm intrigued by the concept of updating a field dynamically without refreshing the page or overwhelming the server with queries. Stackoverflow demonstrates this feature when someone answers our question, and it instantly shows at the top of the page. ...

Obtaining JSON object by using a variable as the key

After developing a .post form that returns a JSON string, I am facing an issue in fetching the data based on the names of the select boxes. Below is an example for better reference. Code Snippet (JavaScript) $(document).ready(function(){ $.post(&apos ...

The chart is not showing up on Angular-Chart.js

Having trouble with Angular-chart.js and can't seem to get it working. Here is the code I have for my JavaScript and HTML page: (function(){ angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope) { $scope.labels = ['20 ...