Modifying the $scope within a controller

I need to update the $scope within the controller based on the object that is being clicked. The current code looks like this:

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

blogApp.controller('blogPostsCtrl', function($scope, $http) {   
    $http.get('http://jsonplaceholder.typicode.com/posts').success(function(data) {
        $scope.posts = data;
        $scope.postsLoaded = 'article--loaded';
    });

    $scope.getPost = function(postID) {
        var currentPost = document.getElementById('post-'+postID);
        $scope.postsLoaded = 'article--loaded';

        $http.get('http://jsonplaceholder.typicode.com/posts/'+postID).success(function(data) {
            $scope.body = data.body;
            currentPost.insertAdjacentHTML('beforeend', '<div class="body body--hidden" id="body-'+postID+'">'+$scope.body+'</div>');

            var currentBody = document.getElementById('body-'+postID);
            setTimeout(function() { currentBody.className = currentBody.className + ' body--visible'; }, 1000); 
            currentPost.classname = 'article one-half desk-one-whole';
        });
    };
});

html:

<div class="site-wrapper">
    <div class="grid-wrapper" ng-controller="blogPostsCtrl">
        <article ng-repeat="post in posts" ng-class="postsLoaded" class="article one-half desk-one-whole" id="post-{{post.id}}" ng-click="getPost(post.id)">
            <header><h2>{{post.title}}</h2></header>
        </article>
    </div>
</div>

In the code above, I am using the getPost function inside the controller and referring to the global wrapper's $scope. How can I ensure it only updates for the specific object being clicked? As a new Angular user, any guidance would be greatly appreciated! :-)

Answer №1

After reading @Matthew Green's response, I can understand why your question may be a bit confusing. It seems like the solution lies in using directives. You will need to create a directive and assign it to its own $scope.

I hope this information proves helpful to you.

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 could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

NG-show does not function properly with Angular validation messages when there are two input fields present

I have created a form with two modes: 'Create' and 'Edit'. Depending on the mode selected, specific div content is displayed in different areas of the layout. The content of the div includes an input field and validation messages relate ...

Transforming a class component into a functional component using React for a session

While working on a React application, I encountered the need for auto logout functionality for inactive users. After referring to this resource, I attempted to convert my class component code to functional components. However, I faced issues as the functio ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...

Sending data from an AngularJS frontend to a Laravel backend using an HTTP

I've been researching, but I can't seem to make sense of anything. I'm new to Laravel and I want to use it as a backend for my AngularJS project. Since I have experience with Angular, here is the controller function where I make an HTTP call ...

Determine whether a subdomain is present within an ajax file in php

Looking for assistance with checking the existence of a 'Subdomain' in a file called '\example\sites'. Here's the code: $form = array() ; $form['name'] = "install"; $form['action'] = "?step=2"; $for ...

Having issues with Exit Property functionality in Framer Motion when using react js

Help Needed: Framer Motion Exit Property Not Working I've been trying to get the exit motion to work on Framer Motion with React JS for over a week now, but everything else seems to be functioning correctly. I have installed the latest version of Fra ...

issue with angular directive not properly binding data

I am curious about the following code: HTML: <div class="overflow-hidden ag-center" world-data info="target"></div> js: .directive('worldData', ['$interval', function($interval) { return { scope: { ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Exploring the differences between JavaScript destructuring and assignment

In my code, I initially used this line: const availableDays = status.availableDays; However, a suggestion was made to replace it with this line: const { availableDays } = status; Both options achieve the same result in one line of code, but I am curious ...

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

What is causing this to function properly only during the initial display of the dialog?

When using ui-bootstrap with the attribute attached to the ok/save button on the dialog, I encountered an issue. The first time my dialog is created, it focuses on the button just as expected. However, every subsequent time it has no effect. .directive(&a ...

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

Guide on adjusting the scroll position in tinyscrollbar on page load

I have integrated tinyscrollbar into my project. One of the options available is contentPosition (Number, indicating the position of the content relative). Yet, I am struggling to modify it as needed. This is how my current JavaScript code looks: $(do ...

Utilizing JS datepicker for multiple input fields sharing a common class

After trying to implement the js-datepicker plugin from https://www.npmjs.com/package/js-datepicker, I ran into an issue. I have multiple input fields in which I want to use the same date picker, so I assigned them all the class 'year'. Unfortuna ...

AngularJS does not run the code inside the ref once directive

Code within the block of this.verifyUserToken does not execute. It appears that the issue may stem from asynchronous calls, as the data returned is not yet available. I am unsure of how to proceed in handling this. this.verifyUserToken = function(){ ...

Cross-origin resource sharing (CORS) is preventing access because the origin and allowed origin match

Utilizing Dockerized Ory Kratos and Angular (www folder hosted via nginx for header modifications) on localhost and attempting to run the following code: const headers = { Accept: 'application/json', }; fetch('http://127.0.0.1:4433/self-s ...