angularjs dynamically set css on html element - javascript

<!DOCTYPE html>
<html ng-app="myApp" class="{{themeClass}}">
<head lang="en">
<meta charset="UTF-8">
<title>Project Title</title>
</head>
<body>
<nav class="header">
<ul class="navbar">
<li>
<span>Project Name</span>
</li>
</ul>
</nav>
<div ng-controller="myCtrl">
</div>
</body>
</html>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.themeClass = something;
})
How to change , class="{{themeClass}}" value dynamically from angularJS code. HTML element is not bind to any controller and also I don't have any directives since I am using spring boot security.
Can someone please let me know how to change "themeClass" variable value dynamically??
Thanks in advance

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="homeCtrl" class="{{themeClass}}">
<head lang="en">
<meta charset="UTF-8">
<title>Project Title</title>
</head>
<body>
<nav class="header">
<ul class="navbar">
<li>
<span>Project Name</span>
</li>
</ul>
</nav>
</body>
</html>
var app = angular.module('myApp', []);
app.controller('homeCtrl', function($scope){
$scope.themeClass = something;
});

Put ng-controller in a parent or the same tag where you want to use the binding.( it should be in the scope not outside it)
Use ng-class="themeClass";
Check the code:
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl" ng-class="themeClass">
<head lang="en">
<meta charset="UTF-8">
<title>Project Title</title>
</head>
<body>
<nav class="header">
<ul class="navbar">
<li>
<span>Project Name</span>
</li>
</ul>
</nav>
</body>
</html>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.themeClass = something;
});

Check This link http://jsfiddle.net/mrajcok/H2Qcn/
<div ng-app="classApp" ng-controller="bootstrapController">
<p>Enter one character at a time for button transitions</p>
<input ng-model="message" />
<button class="btn btn-default" ng-class="{
'btn-danger': isOne(),
'btn-warning': isTwo(),
'btn-info': isThree(),
'btn-success': isFourOrMore()
}">Button State</button>
</div>
var app = angular.module('classApp', []).
controller('bootstrapController', ['$scope', function ($scope) {
$scope.isOne = function () {
if (typeof $scope.message !== 'undefined') {
return $scope.message.length == 1;
} else {
return false;
}
}
$scope.isTwo = function () {
if (typeof $scope.message !== 'undefined') {
return $scope.message.length == 2;
} else {
return false;
}
}
$scope.isThree = function () {
if (typeof $scope.message !== 'undefined') {
return $scope.message.length == 3;
} else {
return false;
}
}
$scope.isFourOrMore = function () {
if (typeof $scope.message !== 'undefined') {
return $scope.message.length >= 4;
} else {
return false;
}
}
div {
padding: 20px;
}
input {
padding: 5px;
font-size:16px;
}
.btn {
transition: all 0.3s linear;
}

Related

Basic JavaScript button interaction

I'm new to JavaScript and Node.js.
I'm trying to get a button in my webpage to call a method in my controller when clicked, but so far I'm getting no response from my controller.
How do I call the .submitEntry() function from my button?
Here's the index.html file:
<!DOCTYPE html>
<meta charset="UTF-8">
<html ng-app='app'>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div ng-controller='GameController' class='container'>
<h1>Palindrome Game</h1>
<h2>Submit a new word!</h2>
<form role='form'>
<div class='form-group'>
<input ng-model="name" class='form-control' placeholder="Your name">
<input ng-model="word" class='form-control' placeholder="Word">
<button ng-click='submitEntry()' class='btn btn-default'>Submit word</button>
</div>
</form>
<h2>Top Scores</h2>
<ul class='list-group'>
<li ng-repeat="score in scores | orderBy:'-points'" class='list-group-item'>
<strong>{{score.name}}</strong> {{score.points}} points
</li>
</ul>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.js'></script>
<script src='ng/app.js'></script>
</body>
And here's the app.js file:
var app = angular.module('app', []);
const button = document.getElementById('myButton');
button.addEventListener('click', function(e)
{
console.log('button was clicked');
});
app.controller('GameController', function($scope, GameService)
{
console.log("Debug 0");
$scope.submitEntry = function()
{
if (typeof $scope.name === 'undefined' || typeof $scope.word === 'undefined')
{
return;
}
var entry = {
name: $scope.name,
word: $scope.word
};
GameService.submitEntry(entry).success(function(points)
{
$scope.word = undefined;
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
};
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
app.service('GameService', function($http)
{
this.getScores = function() {
return $http.get('/api/getScores');
};
this.submitEntry = function(entry) {
return $http.post('/api/submitEntry', entry);
};
});
Thank you very much! Any help that could point me in the right direction will be very appreciated.
Here's a simple button that displays an alert once clicked.
function Channels($scope) {
$scope.test = function() {
alert('button clicked!')
}
}
angular.module('app', [])
.controller('Channels', Channels);
angular.bootstrap(document.body, ['app']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-controller="Channels">
<button ng-click="test()">
test
</button>
</body>

Script is getting executed before I press button

I'm stuck in this code this is a coursera assignment on angularjs. I'm beginner in angular js and new to stackoverflow. This is a code about to find how much a person should it. It counts the number of items and then show the result. Items are seperated by ','.
(function () {
'use strict';
angular.module('LunchCheck', [])
.controller('LunchCheckController', LunchCheckController);
LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
//$scope.msg="";
//console.log($scope.calculate);
$scope.calculate="";
$scope.check = Checker($scope);
}
function Checker(string) {
var str = string.calculate;
console.log(str);
var str1 = str.split(',');
var temp = str1.length;
console.log(temp);
string.msg=message(string,temp);
}
function message(string,temp) {
if(temp > 3) {
return "Too Much!";
}
else if (temp==0) {
return "Aren`t you hungry??";
}
else {
return "Enjoy";
//console.log('Enjoy');
}
}
})();
<!doctype html>
<html lang="en">
<head>
<title>Lunch Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link rel="stylesheet" href="styles/bootstrap.min.css">-->
<style>
.message { font-size: 1.3em; font-weight: bold; }
</style>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="LunchCheck">
<div class="container" ng-controller="LunchCheckController">
<h1>Lunch Checker</h1>
<div class="form-group">
<input id="lunch-menu" type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control" ng-model="calculate">
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="check();">Check If Too Much</button>
</div>
<div class="form-group message">
<!-- Your message can go here. -->
{{msg}}
</div>
</div>
</body>
</html>
Here javascript function is getting executed before I enter any input. I want it to execute after I enter a input. Please help.
Thanks in advance.

Control a div with two checkboxes in angularjs

i am learning AngularJs, any help is much appreciated, trying to display the div content that is checked, if nothing checked the div with 'selected' class name should appear.
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input type="checkbox" class="myCheckbox" ng-model="aCheck" ng-change="checkbox1Func()">A
<input type="checkbox" class="myCheckbox" ng-model="bCheck" ng-change="checkbox2Func()">B
<div ng-if="selected">Hello from div container</div>
<div ng-if="aCheck">Hello from checkbox1</div>
<div ng-if="bCheck">Hello from checkbox2</div>
</body>
</html>
And the script
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected=true;
$scope.checkbox1Func=function(a){
$scope.selected=false;
};
$scope.checkbox2Func=function(b){
$scope.selected=false;
};
if($scope.aCheck === false && $scope.bCheck===false){
$scope.selected=true;
}
// $('.myCheckbox').click(function() {
// $(this).siblings('input:checkbox').prop('checked', false);
// });
});
Your existing logic will work if you check the if condition
if($scope.aCheck === false && $scope.bCheck===false){
$scope.selected=true;
}
inside both the functions checkbox1Func and checkbox2Func.
Wrap the check inside a function and call it on the ng-change event,
$scope.valid = function() {
if ($scope.aCheck === false && $scope.bCheck === false) {
$scope.selected = true;
}
}
HTML
<input type="checkbox" class="myCheckbox" ng-model="aCheck" ng-change="checkbox1Func();valid();">A
<input type="checkbox" class="myCheckbox" ng-model="bCheck" ng-change="checkbox2Func();valid();">B
DEMO
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected = true;
$scope.checkbox1Func = function(a) {
$scope.selected = false;
};
$scope.checkbox2Func = function(b) {
$scope.selected = false;
};
$scope.valid = function() {
if ($scope.aCheck === false && $scope.bCheck === false) {
$scope.selected = true;
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input type="checkbox" class="myCheckbox" ng-model="aCheck" ng-change="checkbox1Func();valid();">A
<input type="checkbox" class="myCheckbox" ng-model="bCheck" ng-change="checkbox2Func();valid();">B
<div ng-if="selected">Hello from div container</div>
<div ng-if="aCheck">Hello from checkbox1</div>
<div ng-if="bCheck">Hello from checkbox2</div>
</body>
</html>

Cant add second ng-controller

I am pretty new in angular/js development so now i stacked with this.
When I add ng-controller="HeaderController" to my HTML code it cant load Angular. If you remove this everything is fine. Why that happened? Thanks for any help and sorry for bad English :)
Code:
(function() {
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController'['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
})();
<!DOCTYPE html>
<html ng-app ="FunStuff">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>LEARN JS</title>
<meta charset="utf-8">
</head>
<body >
<header ng-class = "ColorClass" ng-controller="HeaderController">
<h1>$~/Path_To_Js/</h1>
<button class="changeColorBtn" ng-click="changeColorClass('white')">
ChangeColorButton
</button>
</header>
<div class="wrapper" >
<article ng-controller = "TextController">
<p>There will be some information</p>
<form ng-submit="add()">
<input ng-model="name"><button>Add</button>
</form>
<ul class="buttons" ng-repeat= "n in stuff track by $index">
<li>{{n}}</li>
</ul>
</article>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
As your error says, You are missing , after the header controller,
app.controller ('HeaderController',['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
DEMO
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController',['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
<!DOCTYPE html>
<html ng-app ="FunStuff">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>LEARN JS</title>
<meta charset="utf-8">
</head>
<body >
<header ng-class = "ColorClass" ng-controller="HeaderController">
<h1>$~/Path_To_Js/</h1>
<button class="changeColorBtn" ng-click="changeColorClass('white')">
ChangeColorButton
</button>
</header>
<div class="wrapper" >
<article ng-controller = "TextController">
<p>There will be some information</p>
<form ng-submit="add()">
<input ng-model="name"><button>Add</button>
</form>
<ul class="buttons" ng-repeat= "n in stuff track by $index">
<li>{{n}}</li>
</ul>
</article>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
(function() {
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController',['$scope',function($scope){
//^^ missing comma here
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
})();

Issue with Angular don't see my data

I want that in the init to bind the model of my controller the init is called but I don't see any data what is wrong ?
Index.html
<!DOCTYPE html>
<html ng-app="I-Sign">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name="viewport" content="width=device-width" />
<title>Sign Language Application</title>
<link rel="stylesheet" href="scripts/jquery.mobile-1.4.5.css" />
<script type="text/javascript" charset="utf-8" src="scripts/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/angular.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/lodash.js"></script>
<script src="mainController.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl" ng-init="init()">
<div id="categories">
     <ul data-role="listview" data-inset="true">
         <li ng-repeat="category in ctrl.data.categories"><a ng- click="ctrl.showWords(category)" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{category.name}}</h1>
        </a>   
        </li>
</ul>
</div>
<div id="words">
    <ul data-role="listview" data-inset="true">
            
        <li ng-repeat="word in ctrl.currentWords"><a ng-click="ctrl.showMovie()" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{word.name}}</h1>
        </a>                 
        </li>
</ul>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-hide ng-click="ctrl.showCategories()">
</div>
</div>
mainController.js
var myApp = angular.module('I-Sign',[]);
myApp.controller('MainCtrl', ['$scope', function($scope) {
var self = $scope;
$scope.init = function () {
var that = this;
that.getData();
self.currentWords = [];
}
$scope.$watchCollection(function () {
//var that = this;
return self.data;
}, function () {
console.log("Changed");
});
$scope.getData = function () {
var that = this;
$.getJSON('data/database.json', function (data) {
that.data = data;
});
}
$scope.showCategories = function () {
var that = this;
$("#words").addClass("ng-hide");
$("#categories").removeClass("ng-hide");
$("#upBtn").assClass("ng-hide");
}
$scope.showWords = function (category) {
var that = this;
that.currentWords = [];
$("#categories").addClass("ng-hide");
$("#words").removeClass("ng-hide");
$("#upBtn").removeClass("ng-hide");
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
}]);
Since you used jquery to get your data, you need to run a .$apply() as the code happened outside of angulars knowledge
$.getJSON('data/database.json', function (data) {
that.data = data;
$scope.$apply();
});
Alternatively you should not be using jquery at all and instead inject $http in (like you did with $scope) and use that:
$http.get('data/database.json')
.success(function(data){
that.data = data;
});
Additionally change the following:
$scope.showCategories = function () {
$scope.showCategories = true;
}
$scope.showWords = function (category) {
that.currentWords = [];
$scope.showCategories = false;
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
and your html to:
<div id="categories" ng-show="showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="category in ctrl.data.categories">
<a ng-click="ctrl.showWords(category)" href="#">
<img src="images/Can_I.png">
<h1>{{category.name}}</h1>
</a>
</li>
</ul>
</div>
<div id="words" ng-show="!showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="word in ctrl.currentWords">
<a ng-click="ctrl.showMovie()" href="#">
<img src="images/Can_I.png">
<h1>{{word.name}}</h1>
</a>
</li>
</ul>
</div>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-show="!showCategories" ng-click="ctrl.showCategories()">
</div>

Categories

Resources