Exploring a new path with Angular

I'm attempting to dynamically change the sp-right class to sp-left in Angular:
Html

<span class="sp-right">
    <label>
        Number:
    </label>
</span>

Directive

app.directive("buttonThatTrigger", function () {
    return {
        restrict: 'C',//target all elements with class button-that-trigger
        link: function (scope, element, attrs) {
            element.click(function(){
               $('.sp-right, .sp-left').toggleClass("sp-right sp-left");
            });
        }
    };
});  

Everything works perfectly, but when I navigate back to the page the changes revert back to the original class!
Any suggestions on how to fix this issue?

Answer №1

I'm not sure what your specific needs are, but have you considered utilizing ngClass for this task?

<div ng-class='toggleClass(position)' ng-click='position = !position'>

Then you can implement the following logic:

$scope.position = true;

// true=align-right, false=align-left
$scope.toggleClass(pos){
  return pos? "align-right" : "align-left";
};

Answer №2

In order to maintain the state (such as the direction) in your application, you can store it either in a controller that is not affected by ui-router or preferably in a service (.service|.factory|.value).

For instance:

app.value('layoutState', {
        direction: 'left'
    });

Once the state is securely stored, you can update your implementation in a more "angularish" manner:

<span class="{{layoutState.direction === 'left' ? 'div-left' : 'div-right'}}">
    <label>
        Title:
    </label>
</span>

Your custom directive:

app.directive("triggerButton", ['layoutState', function (layoutState) {
    return {
        restrict: 'C',//target all elements with class trigger-button
        link: function (scope, element, attrs) {
            scope.layoutState = layoutState;
            element.click(function(){
                layoutState.direction = layoutState.direction === 'left' ?
                    'right' : 'left';
            });
        }
    };
}]);  

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

Implementing a validator based on the operator selection in react-querybuilder

Is it possible to add validators to fields that are only active when using the like operator? For example, if the like or unlike operators are used in the phoneNumber field without the % sign, it should be invalid. If the = operator is used, the % sign sho ...

Is it possible to transform an array of objects into a new array of objects?

After searching for a similar question, I realized none of them really addressed my issue... EDIT: My main goal is to create a reusable dropdown component where I can pass items as props directly. These items need to be objects with both a key (for the fi ...

Distinguishing the scope binding in AngularJS: Understanding the variance between {foo : ""=""} and {foo : ""=myFoo

While developing web applications in angular, I have come across two different methods for binding variables on the scope. Despite my efforts to understand the difference between them, I always seem to be mistaken. After conducting extensive research, I ha ...

Error: Next.js is throwing a SyntaxError due to encountering an unexpected token 'export'

I encountered an issue when trying to render the following code: SyntaxError: Unexpected token 'export' (project path)/node_modules/react-syntax-highlighter/dist/esm/styles/prism/index.js Everything seems to work as expected initially, but then ...

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

Using Previous and Next Buttons in Bootstrap Tabs for Form Navigation

I am currently facing a challenge in splitting a form into multiple tabs and encountering issues with the next and previous buttons on the second and third tabs. My goal is for the tabs at the top to change state as you cycle through them by clicking the ...

In what way can you establish a boundary for a border?

My goal is to create a 10x10 grid with randomly placed black boxes, but I am facing an issue in my game setup: https://i.sstatic.net/uKy06.png Currently, the 5 black boxes are generated randomly in a row, sometimes exceeding the border and breaking the c ...

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

Sending JSON data from AngularJS to Django REST API using POST method

Currently, I am working on an app using AngularJS and relying on an external API that is built with Django. To make API calls, I have been utilizing Restangular (although I've tried $http as well with the same results). By default, for post requests ...

Can lazy loading be implemented for the video tag using JavaScript?

Currently, I am in the process of working on a project that entails incorporating three videos onto the homepage. However, loading them simultaneously is causing a significant decrease in load time. In addition, I prefer to utilize the <video/> tag ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

Answer found: How to effectively filter data arrays in a React client application

I've been working on mapping the GraphQL data onto a React app and I'm facing an issue with making the filtration dynamic for user input. Currently, I am using .filter() to apply client-side filtration but struggling to figure out how to make it ...

Access the contents of objects during the creation process

I am currently in the process of creating a large object that includes API path variables. The challenge I am facing is the need to frequently modify these API paths for application migration purposes. To address this, I had the idea of consolidating base ...

javascriptif the number is a whole number and evenly divisible

I am currently developing a script that tracks the distance traveled by some dogs in meters. It is basically just a gif running in a loop. What I want to achieve now is to display an image every 50 meters for a duration of 3 seconds. Here's my attempt ...

Django Ajax filter displaying issue on HTML page

I'm uncertain about the correctness of my Ajax implementation. When using Django's built-in tags, the objects I pass through Ajax are not appearing on my template HTML page. view_results.html <div> <input id="search" name="search" t ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

Unlocking the true potential of JSON data encoding in PHP

While attempting to retrieve an object from my controller, the console.log(response) function displays the correct value: [ { "itemValue":100, "itemUnit":"2" } ] However, when trying to access the object using ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

Is there a jQuery alternative to XMLHttpRequest's upload functionality?

When working with the HTML5 File API, the upload process is handled through an object called upload within the XMLHttpRequest. I am currently following a tutorial on this topic, you can find it here (or use the Google cache mirror since the original link i ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...