Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting css style from controller angularjs

Tags:

angularjs

I've been at this for 30 minutes and cannot figure out what I am doing wrong...

HTML:

<div ng-controller="main">
    <div ng-style="mapheight">
        <google-map center="center" zoom="zoom" style="height: inherit;"></google-map>
        </div>
</div>

CONTROLLER:

angular.module('csApp.controllers', ["google-maps"]).
    controller("main", function($scope) {
        $scope.mapheight = "{'min-height':" + getHeight() + "px;}";
        $scope.center = {
            latitude: 45,
            longitude: -73
        };
        $scope.zoom = 8;

        function getHeight() {
            return (window.innerHeight * .70);
        }
    })

No style is being applied to my div at all.

I can get it pass the variable when I put {{mapheight}} in my template but then I have to pass it to the style property, which is apparently not how I should do it.

What am I doing wrong here? This is my first day with angular and I'm almost in tears because I can't even resize a div.

Thank you!

here is the change in my controller:

  $scope.mapHeight = { 'min-height': getHeight() };
like image 342
Ray Suelzer Avatar asked Oct 15 '13 00:10

Ray Suelzer


People also ask

How do I style in AngularJS?

AngularJS ng-style DirectiveThe ng-style directive specifies the style attribute for the HTML element. The value of the ng-style attribute must be an object, or an expression returning an object. The object consists of CSS properties and values, in key value pairs.

How do you use important in Ngstyle?

ng-style does not support ! important . So alternate is to use ng-class instead of ng-style , it will solve the problem. If you want to use ng-style specifically then try to write within html itself- please don't try to write within any function.

Can you create controller in AngularJS?

AngularJS ControllersAngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

Can we have two controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application.


1 Answers

ng-style takes an object binding, so $scope.mapheight should be an object rather than a string. i.e.

$scope.mapheight = {
    'min-height': getHeight() + "px"
};

The ng-style attribute takes an expression, so putting the string version directly in the HTML

ng-style="{'min-height': '40px'}"

would work as it would be evaluated and an object would be created. Setting ng-style="mapheight" is evaluated as taking the value of mapheight from $scope so $scope.mapheight needs to be an object.

like image 158
Andyrooger Avatar answered Oct 12 '22 09:10

Andyrooger