Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my API into the HTML.

HTML

<!DOCTYPE html>
    <html lang="en" ng-app="tophueApp">
        <body>
            <div ng-view></div>

            <script type="text/ng-template" id="two_column.html">
                <div id="two_column_container">
                    <div id="left_pane">
                    <div class="material_background">
                        <div ng-repeat="post in posts" class="post_block">
                            <a href="/post/{{post.pk}}/{{post.url_safe_title}}" class="title_text" onclick="return show_inline(this,'{{post.source_site}}')">
                                <span ng-if="post.is_NSFW" class="is_NSFW">
                                    NSFW
                                </span>

                                {{post.title}}
                            </a>
                <span class="post_info">
                    </span>
                </span>
                </div>
                </div>
                    </div>
                </div>
            </script>

            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.js"></script>
            <script src="base.js"></script>
            <link rel="stylesheet" href="base.css" />
        </body>
    </html>

base.js

var tophueApp = angular.module('tophueApp', ['ngRoute']);

tophueApp.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.
      when('/topic/:topicName/', {
        templateUrl: 'two_column.html',
        controller: 'TopicController'
      }).
      when('/', {
        templateUrl: 'two_column.html',
        controller: 'HomeController'
      }).
      otherwise({
        redirectTo: '/'
      });

     $locationProvider.html5Mode({
                     enabled: true,
                     requireBase: false
              });
  }]);

tophueApp.controller('TopicController', ['$scope', '$http', '$routeParams',
    function($scope, $http, $routeParams) {
        $http.get('/api/topic/'+$routeParams.topicName+'/').success(function(data) {
        $scope.posts = data;
    });
}]);

tophueApp.controller('HomeController', ['$scope', '$http',
    function($scope, $http) {
        $http.get('/api/home.json').success(function(data) {
        $scope.posts = data;
    });
}]);

When accessing a page like /topic/topicname, I receive the correct JSON response from my API, but the data doesn't bind to the partial template.

EDIT: (json response)

[{
        "user" : "jack",
        "source_id" : "rX5n0oP",
        "topic" : "swag",
        "title" : "http://i.imgur.com/rX5n0oP.jpg",
        "url_safe_title" : "httpiimgurcomrx5n0opjpg",
        "is_NSFW" : false,
        "source_url" : "http://i.imgur.com/rX5n0oP.jpg",
        "pk" : 8,
        "source_site" : "imgur-img"
    }, {
        "user" : "jack",
        "source_id" : "QW8Sp1O",
        "topic" : "swag",
        "title" : "http://imgur.com/QW8Sp1O",
        "url_safe_title" : "httpimgurcomqw8sp1o",
        "is_NSFW" : false,
        "source_url" : "http://imgur.com/QW8Sp1O",
        "pk" : 1,
        "source_site" : "imgur-img"
    }]

Answer №1

If you're having trouble getting your templates to bind to $scope, try using static json instead of api calls. Check out this code pen for an example: http://codepen.io/anon/pen/EazprP

$scope.posts=[{
    title:"Home"
}]

It's possible that the issue lies with your json response. Can you share the json data?

Answer №2

Looks like the angular.js tags were causing issues with my django backend tags. I made a simple adjustment

$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');

to alter the search criteria for angular.js and it resolved the problem :)

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

Guide to displaying a component within the Vue instance

I am currently in the process of developing a Nuxt module that will not interfere with the main Nuxt application. My approach involves creating a separate Vue instance and mounting it as a child node under the body element, similar to a child node to the _ ...

Transforming screen recording video chunks from blob into multipart for transmission via Api as a multipart

Seeking guidance in Angular 8 - looking for advice on converting screen recorded video chunks or blogs into a multipart format to send files via API (API only accepts multipart). Thank you in advance! ...

How can we configure AngularJS UI-Bootstrap to set a minimum date of 90 days ago and a maximum date of today?

I am currently working on an AngularJS and UI-Bootstrap app that includes a datePicker with certain date restrictions. As someone new to Angular, I am seeking advice on how to set the minDate to 90 days ago and the maxDate to today's date. Check out ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

Identifying fluctuations in unprocessed data

Currently in the process of developing a web application that serves as a dashboard for monitoring storage tank levels. It gathers data from various sensors inside tanks and saves this information in a database. The tool is created using express / node.js. ...

Intersecting realms document

Currently I am working on a web store using Magento Go. Unfortunately, this platform does not support server side scripting languages such as PHP. Despite this limitation, I still need to save order data post successful checkout and share it with my shippi ...

Before beginning my selenium scripts, I need to figure out how to set an item using Ruby in the browser's localStorage

Before running my selenium scripts, I am attempting to store an item in the browser's localStorage. I attempted to clear the local storage using this command: driver.get('javascript:localStorage.clear();') This successfully cleared the lo ...

Handle all link clicks on the webpage

My challenge is that some users are required to utilize a virtual desktop in order to access specific information on my website. However, within the virtual environment, there are links leading to external content that do not function properly. I am seekin ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

The absence of data in a c# web api controller is causing issues with jQuery AJAX post requests

When I am sending data to a c# web api controller, I use the following method: $.ajax({ type: "POST", url: "menuApi/menu/Cost", data: JSON.stringify(order), contentType: "application/json", success: function (data) { window.alert(&apo ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...

How can I implement internal redirection within a ReactJS application?

As someone who is new to React, I've been exploring how to internally redirect pages in ReactJS. Specifically, I have two pages named "register" and "register2". In the register page, the process involves checking if an email exists in the database. I ...

How to retrieve JSON data from an AngularJS HTTP POST request using a servlet

While attempting to send data in JSON format from an angularJS client using a post http request and retrieve it through a j2ee servlet, I encountered an error. Strangely, my complete data can only be accessed using the getParameterNames method in my servle ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

software tool for managing state transitions

Can anyone recommend a superior javascript library for workflows? Right now, I'm utilizing Joint JS, but I require something with a more visually appealing interface (users tend to prefer that). ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...

Using PHP to send asynchronous requests to the server can greatly enhance

I have almost completed my project, but I am facing an issue with reading the data sent to the server. function main() { jQ(document).on("keyup", "form input", function () { var data = new FormData(); var value = jQ(this).val(); da ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...