Hi I am new to Angularjs. I am learning how to share data between two controllers using dataservice. Looking at the tutorial I made my own program but it is not working. Can anyone suggest what I am doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Services</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
</head>
<body>
<div ng-app="dataServiceApp">
<div ng-controller="ChildCtrl">
<h2>First controller</h2>
<button>+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button>+</button>{{Holder.value}}
</div>
</div>
<script>
var myapp = angular.module("dataServiceApp",[]);
myapp.factory('Holder', function() {
return {
value: 0
};
});
myapp.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
myapp.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
</script>
</body>
</html>
You have forgotten to register onclick listeners to the buttons:
<button ng-click="increment()">+</button>{{Holder.value}}
Hope this helps. Complete working example below:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Services</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
</head>
<body>
<div ng-app="dataServiceApp">
<div ng-controller="ChildCtrl">
<h2>First controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button ng-click="increment()">+</button>{{Holder.value}}
</div>
</div>
<script>
var myapp = angular.module("dataServiceApp",[]);
myapp.factory('Holder', function() {
return {
value: 0
};
});
myapp.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
myapp.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
</script>
</body>
</html>
p.s. I also fully agree with JB Nizet's comment: check whether you really need to learn AngularJS instead of Angular 2-7/VueJS/React.
Related
I have a simple model with a list of names and corresponding images. I'm trying to click on the name of the image and load the corresponding image. I can't get the image to load. The list of names appears on the page, but when I click them nothing happens. Please help with code. Thx!
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel ="stylesheet" type "text/css" href ="clicker.css">
<script type = "text/javascript" src="Libs/angular.js"></script>
<script type = "text/javascript" src="js/CatClickerMe.js"></script>
<body>
<div ng-controller = "MainController">
<div ng-repeat = "cat in options.catList">
<h3 ng-click = "MainController.selectCat($index)">{{cat.name}}</h3>
<h3>{{MainController.selectedCat.name}}</h3>
<img ng-src = "{{MainController.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>
JS
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
$scope.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
vm.selectCat=function(pos) {
vm.selectedCat = angular.copy(vm.catList[pos]);
vm.selectedCat.pos = pos;
};
activate();
function activate() {
}
})
})();
You are mixing up $ scope and vm, go with one approach. You need to use controller as syntax in the template,
<div ng-controller = "MainController as vm">
DEMO
(function() {
"use strict";
angular.module('myApp',[]);
angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
vm.selectCat = selectCat;
this.options = {
catList:[
{
name: 'Fluffy',
images: 'images/Fluffy.jpeg'
},
{
name: 'Tabby',
images: 'images/tabby.jpeg'
}
],
};
function selectCat(pos) {
vm.selectedCat = pos;
};
})
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<meta charset="UTF-8">
<title>Cat Clicker</title>
<body>
<div ng-controller = "MainController as vm">
<div ng-repeat = "cat in vm.options.catList">
<h3 ng-click = "vm.selectCat(cat)">{{cat.name}}</h3>
<h3>{{vm.selectedCat.name}}</h3>
<img ng-src = "{{vm.selectedCat.images}}" >
</div>
</div>
</div>
</body>
</html>
I am working on a stock application using Spring Boot. I have stock data from external API which looks like this:
{{stock.dates}} = [2017-05-04, 2017-05-03, 2017-05-02, 2017-05-01,
2017-04-28, 2017-04-27, 2017-04-26, 2017-04-25, 2017-04-24, 2017-04-21]
{{stock.stockValues}} = [150.85, 151.8, 152.78, 152.46, 150.25, 147.7,
146.56, 146.49, 145.47, 143.68]
My index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Stock app</title>
<script>
<!-- Many scripts here-->
</script>
</head>
<body ng-app="App">
<navbar-menu></navbar-menu>
<div class="container" ng-view></div>
</body>
</html>
My stock.html:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
<!-- Many scripts here-->
</script>
</head>
<body>
<div id="spinner" class="spinner" ng-show="loading">
<img src="https://www.yugma.com/images/loading-animation-7.gif" />
</div>
<!-- Page Content -->
<div class="container" ng-show="content">
<div class="panel">
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Stock symbol:</h5>
</div>
<div class="col-md-1">{{stock.symbol}}</div>
<div class="col-md-9"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Last refreshed:</h5>
</div>
<div class="col-md-3">{{stock.lastRefreshed}}</div>
<div class="col-md-8"></div>
</div>
<div class="row">
<div class="col-md-2">
<h5>Last price:</h5>
</div>
<div class="col-md-3">{{stock.stockValues[0]}}</div>
<div class="col-md-8"></div>
</div>
</div>
</div>
</div>
My controller.js:
(function(angular) {
'use strict';
var App = angular.module('App');
App.controller('StockController', [ '$scope', '$http', '$routeParams',
'$rootScope', function($scope, $http, $routeParams, $rootScope) {
$scope.init = function() {
if ($rootScope.stockID !== undefined) {
$scope.getStockData($rootScope.stockID);
return;
} else if ($routeParams.stockID !== undefined) {
$rootScope.stockID = $routeParams.stockID;
} else {
$rootScope.stockID = 'FB';
}
$scope.getStockData($rootScope.stockID);
};
$scope.getStockData = function(stockID) {
$scope.loading = true;
$scope.content = false;
$http.get('/stock', {
params : {
stockID : encodeURI(stockID)
}
}).then(function(response) {
$scope.showError = false;
$scope.stock = response.data;
$scope.stockAvailable = true;
}, function(response) {
$scope.showError = true;
}).finally(function() {
// called no matter success or failure
$scope.loading = false;
$scope.content = true;
});
};
$scope.init();
} ]);
})(window.angular);
Now what I need to do is to create a Google Chart using this data (dates vs stock values)
How can I do it?
Also, when I tried to draw a static example chart from Google Charts Tutorial I could only do it in my index.html, when I put the same definition in stock.html, the chart didn't work, do you have any idea why?
I have attached plunker link for that.
This is my html
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-cookies.js"></script>
<script src="https://rawgithub.com/angular-translate/bower-angular-translate/master/angular-translate.min.js"></script>
<script src="https://rawgithub.com/angular-translate/bower-angular-translate-storage-cookie/master/angular-translate-storage-cookie.js"></script>
<script src="https://rawgithub.com/angular-translate/bower-angular-translate-loader-static-files/master/angular-translate-loader-static-files.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="someController">
<div id="parent">
<h1>{{'HEADLINE' | translate }}</h1>
<button ng-click="switchLanguage('de_DE')" translate="LANG_DE_DE"></button>
<button ng-click="switchLanguage('en_US')" translate="LANG_EN_US"></button>
<button id="myButton" class="float-right submit-button" ng-click="showDiv()" >Click here</button>
</div>
<script type="text/javascript">
</script>
<div id="hello">
<span name="new" id="newpage" style="display: none;">
<h1 class="xx">{{'HELLO'| translate }}</h1>
</span>
</div>
</body>
</html>
app.js
angular.module('myApp', ['pascalprecht.translate', 'ngCookies']);
angular.module('myApp').config(['$translateProvider',
function($translateProvider) {
var language = (window.navigator.userLanguage || window.navigator.language).toLowerCase();
console.log(language);
$translateProvider.registerAvailableLanguageKeys(['de_DE', 'en_US'], {
'en_US': 'en_US',
'en_UK': 'en_US',
'en': 'en_US',
'de': 'de_DE'
});
$translateProvider.useStaticFilesLoader({
prefix: 'lang_',
suffix: '.json'
});
$translateProvider.preferredLanguage('en_US');
// $translateProvider.use('de');
$translateProvider.useCookieStorage();
$translateProvider.fallbackLanguage("de_DE");
}
]);
angular.module('myApp').controller('someController', ['$scope', '$translate',
function($scope, $translate) {
$scope.switchLanguage = function(key) {
$translate.use(key);
};
$scope.showDiv = function()
{
var html = document.getElementById("newpage").innerHTML;
var container = document.createElement("span");
container.innerHTML = html;
document.getElementById("parent").appendChild(container);
}
}
]);
lang_de_DE.json
{
"HEADLINE": "Überschrift",
"LANG_DE_DE": "Sprache: Deutsch",
"LANG_EN_US": "Sprache: Englisch",
"HELLO" :"Neue Seite"
}
lang_en_US.json
{
"HEADLINE": "Headline!",
"LANG_DE_DE": "Lang: German",
"LANG_EN_US": "Lang: English",
"HELLO" :"New page"
}
In this New page text (show div function) wont update when i change language.
Plunker link https://plnkr.co/edit/1pBWUFZMbHx4zKzNRKzD?p=preview
Use ng-repeat, do not manipulate DOM inside the controller.
Change your span in something like this:
<span ng-repeat="div in divs">
<h1 class="xx">{{'NEWPAGE'| translate }}</h1>
</span>
and your showDiv function:
scope.divs = [];
$scope.showDiv = function()
{
$scope.divs.push({});
}
Updated plunker here.
You need clearly to think in a more angularjs way. DO NOT pollute your controller with jquery and dom manipulation code. That's not for what angularjs is for.
Read the docs on ng-repeat here.
I am new to learning AngularJs and stuck at this particular error. Can't seem to find the reason behind this error. Any help will be appreciated.
I am using AngularJs 1.2.
Please advise.
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
</head>
<body ng-app="Heirarchy">
<div ng-controller="ParentController">
<div ng-controller="ChildController">
<a ng-click="sayHello()">Say hello</a>
</div>
{{ person }}
</div>
<script type="text/javascript">
var app = angular.module("Heirarchy",[]);
app.controller("ParentController",function($scope){
$scope.person = {greeted:false};
});
app.controller("ChildController",function($scope) {
$scope.sayHello = function(){
$scope.person.name="Blade";
$scope.person.greeted = true;
}
});
</script>
</body>
</html>
Update your code
Insert ng-app="your module name" in your html tag, and do not repeat ng-app in your app
<!doctype html>
<html ng-app="Heirarchy">
<head>
</head>
<body>
<div ng-controller="ParentController">
</div>
<div ng-controller="ChildController">
<a ng-click="sayHello()">Say hello</a>
</div>
{{ person }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("Heirarchy", []);
app.controller("ParentController", function ($scope) {
$scope.person = { greeted: false };
});
app.controller("ChildController", function ($scope) {
$scope.sayHello = function () {
$scope.person.name = "Blade";
$scope.person.greeted = true;
}
});
</script>
</body>
</html>
Say I've got AdamController as adam and AnujController as anuj. I want anuj.anujProp to have a j appended to it every time adam.adamProp changes.
How could this be done? What is the best way?
Here are 4 possible ways that I came up with. I ranked them in the order that I personally feel is best.
Events - http://plnkr.co/edit/4AD8e47DaOSuutrphIkN?p=preview
Method on a Factory - http://plnkr.co/edit/Vixab8LjDtow5YYfnlMV?p=preview
Factory + $watch - http://plnkr.co/edit/1zVZ9EDarCGPOMZvrJMd?p=preview
$scope inheritance - http://plnkr.co/edit/3b7tzPI5Y4CcwWYXUk25?p=preview
The $scope inheritance approach just feels "messy". I like the event driven approach over the factory approaches because I feel like there's a sort of overhead associated with the factories, and if it's only going to be used for this one purpose, the overhead isn't worth it. Plus, this just seems to be exactly what events are for. I put (2) ahead of (3) because the $watch hurts performance.
Events
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($rootScope) {
var vm = this;
vm.prop = 'adam';
vm.update = function() {
$rootScope.$broadcast('propChange');
};
}
function AnujController($scope) {
var vm = this;
vm.prop = '';
$scope.$on('propChange', function(event) {
event.currentScope.anuj.prop += 'x';
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.prop' ng-change='adam.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.prop }}</p>
</div>
</body>
</html>
Method on a Factory
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
anujProp: 'anuj',
update: function() {
this.anujProp += 'j';
}
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory) {
var vm = this;
vm.factory = Factory;
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='initial' ng-change='adam.factory.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.anujProp }}</p>
</div>
</body>
</html>
Factory + $watch
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
shared: 'shared',
related: 'related'
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory, $scope) {
var vm = this;
vm.factory = Factory;
$scope.$watch('anuj.factory.related', function(newValue, oldValue, scope) {
scope.anuj.factory.related = newValue.toUpperCase();
});
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.factory.shared'>
<input ng-model='adam.factory.related'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.shared }}</p>
<p>{{ anuj.factory.related }}</p>
</div>
</body>
</html>
$scope inheritance
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($scope) {
var vm = this;
vm.adamProp = 'adam';
vm.update = function() {
var anuj = $scope.$parent.$$childTail.anuj;
anuj.anujProp += 'j';
};
}
function AnujController() {
var vm = this;
vm.anujProp = 'anuj';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="AdamController as adam">
<input ng-model="adam.adamProp" ng-change="adam.update()" />
</div>
<div ng-controller="AnujController as anuj">
<p>{{ anuj.anujProp }}</p>
</div>
</body>
</html>