linking ng-style through live html

I am encountering an issue with dynamic data stored in the database. When trying to apply a style to a div element retrieved from the server response, I am facing difficulties with implementing it using ng-style.

If the data is static, everything works fine. Here is an example of my static HTML:

<div ng-controller="empty" >
    <div>
        <div ng-bind-html="validData | unsafe"/>
    </div>
</div>

However, when the data is fetched from the database, the styling does not get applied as expected. Below is the code snippet for the dynamic content:

<div class="row">   
    <div ng-style="visualization" class="col-md-4">.col-md-2</div>   
    <div ng-style="visualization" class="col-md-8">.col-md-8</div> 
</div> 
<div class="row">
    <div ng-style="visualization" class="col-md-4">.col-md-8</div>
</div>

To tackle this issue, I have set up a controller that handles the data retrieval and styling assignment:

$http.get(globalVars + 'page/' + lastParam)
  .success(function (data) {
    $scope.empty = data;

    $scope.validData = $scope.empty.layout.schema;

    $compile($scope.validData);

    if(typeof $rootScope.mode == 'undefined' || $rootScope.mode =='edit'){
       $scope.visualization = {
         "border-style": "dashed"
       }
    }
    else{
       $scope.visualization = {
         "border-style": "none"
    }
  }
  })
  .error(function (data) {
});

Despite setting the styling in the controller, the ng-style directive is not properly binding the styles to the Angular application. Any assistance on resolving this issue would be greatly appreciated. Thank you!

Answer №1

You can utilize the $compile(html) function to get a new function that accepts the $scope variable as a parameter. One way to do this is by following this example:

$scope.validData = $compile($scope.validData)($scope);

With this approach, your controller code could be structured as shown below:

$http.get(globalVars + 'page/' + lastParam).success(function (data) {
  $scope.empty = data;

  $scope.validData = $scope.empty.layout.schema;
  if(typeof $rootScope.mode == 'undefined' || $rootScope.mode == 'edit') {

    $scope.visualization = {
      "border-style": "dashed"
    }
  } else {
    $scope.visualization = {
      "border-style": "none"
    }
  }

  $scope.validData = $compile($scope.validData)($scope);

}).error(function (data) {

});

There are alternative methods to achieve the same result, such as using CSS. One option is to apply a conditional class with ng-class on the outer div:

<div ng-class="{'edit-mode': editModeEnabled }" ng-bind-html="validData | unsafe"/>

Then, in your CSS file, define the styles based on the conditional class:

.edit-mode .row > div { 
  border-style: dashed;
}

Remember to set editModeEnabled in your controller:

$scope.editModeEnabled = $rootScope.mode === 'edit';

Answer №2

Thank you for your helpful advice!

span ng-class="{'edit-active': isActiveEditing}" ng-bind- html="validatedInfo | safe"/>

In the Cascading Style Sheets:

.edit-active .section > span { 
  border-style: dotted;
}

Best regards

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

Using Javascript to Conceal Button for Unauthenticated Users

Our website is currently running on an outdated e-commerce CMS platform, which limits my options due to my beginner level skills in JavaScript and jQuery. One specific issue we are facing is the need to hide Prices and Add to Cart buttons for users who ar ...

Exploring the concept of Promises through the lens of recursion

I am dealing with a MongoDB collection that looks like this [ { "classId": "1", "name": "Input", "definition": [ { "property": [ { "classId": "12", "name": "One" }, { ...

Transform an array of strings into an array of floating point numbers using AngularJS

Hey everyone! I'm having trouble converting an array of strings into floats. When using map(parseFloat), I'm only getting integer numbers. Could the issue be with the commas in 40,78 causing parseFloat to interpret it as 40 instead of 40.78? Her ...

Leveraging ngPaste in conjunction with Angular Formly

I am currently utilizing Angular Formly for constructing a basic form. I am in need of disabling paste functionality in one of the input fields. Previously, I managed to disable the ng-Paste default event by following the instructions provided in this res ...

Position the text alongside the Facebook emblem

I am having trouble getting the text Follow Us to align on the far right next to the Facebook Icon. I added the float:right property, but it is not working as expected. Here is the code snippet: <a href="#" target="_blank" style="font-family: Arial, ...

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

Is it possible to monitor two variables in AngularJS, one of which is the location path?

I'm attempting to trigger a function when there is a change in the location path or when an object within a service is modified. However, I am unable to get the function to execute at all. var customSettings = { value : service.cache.MY_V ...

Are JQuery functions affected when navigating between pages in smart-tables?

Apologies if this question has been answered before or seems obvious. I couldn't find a solution after searching, and as someone new to web development, I might be going in circles here. Issue: I've integrated the smart-table extension () into ...

What is the correct way to bind by reference when utilizing a function that returns an object?

I currently have an object in my Component: this.user = Authentication.user; It's working perfectly fine as it copies the reference. So, if Authentication.user changes, this.user in my Component also changes accordingly. However, I am curious to kn ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Animation of CSS elements sliding up on the page, with the element briefly appearing before the slide begins

My CSS animation involves a page scrolling from the bottom to the top when selected. The problem I'm facing is that the page briefly appears in its top position before disappearing to scroll from the bottom to the top. How can I prevent the page from ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

How to achieve the functionality of ocibindbyname in JavaScript

I am currently utilizing an HTA page that is coded in JavaScript to monitor various Oracle tables. My goal is to optimize the Oracle query caching by using bind variables, similar to how I implemented it in a PHP environment with this code: $sql = "selec ...

Strange problem in AngularJS: Directive caught in a loop with a dictionary

I recently developed a new directive that looks like this: app = angular.module('sapp', []) .config(['$interpolateProvider', function ($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvid ...

Using JavaScript Object Constructor to alter text color

Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My quer ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Using expressJS and MongoDB to create a secure login and registration system

I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...