Not able to run angularjs code on the computer - angularjs

Not able to run the angular js code in the following program on my pc. It is working in the plunker editor online.Please let me know if i need to download any thing before i will be able to run the code . Thanks in advance
Html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The angularjs app!</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="C:\Users\komar\Desktop\script.js"></script>
</head>
<body>
<div ng-app="MyModule" ng-controller="MyController as ctrl">
<b>Invoice:</b><br>
<div>
Quantity:<input type = "number" min = 0 ng-model = "ctrl.quantity" required><br>
Costs:<input type = "number" min=0 ng-model="ctrl.costs" required>
<select ng-model="ctrl.selCur">
<option ng-repeat = "c in ctrl.currencies">{{c}}</option>
</span><br>
<b>Total:</b><span ng-repeat= "c in ctrl.currencies">
{{ctrl.convert(c) | currency:c}}
</span><br>
<button class ="btn" ng-click="ctrl.createAlert()">Pay</button>
</div>
</div>
</body>
</html>
Javascript code:
var app = angular.module('MyModule');
app.controller('MyController',[MyService,function MyController(MyService){
this.quantity = 1;
this.costs =2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur){
return MyService.currentCurrencies(this.quantity*this.costs,this.selCur,baseCur);
}
this.createAlert = function createAlert(){
window.alert('Thanks!');
};
}]);
app.factory('MyService',function(){
var currencies= ['USD','EUR','CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount,selCur,baseCur){
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});
I am not able to run this code . please help me fix the issues and help run the code
Even this code is not working
HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-guide-concepts-21-production</title>
<script src="//code.angularjs.org/1.7.7/angular.min.js"></script>
<script src="finance2.js"></script>
<script src="invoice2.js"></script>
</head>
<body >
<div ng-app="invoice2" ng-controller="InvoiceController as invoice">
<b>Invoice:</b>
<div>
Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
</div>
<div>
Costs: <input type="number" min="0" ng-model="invoice.cost" required >
<select ng-model="invoice.inCurr">
<option ng-repeat="c in invoice.currencies">{{c}}</option>
</select>
</div>
<div>
<b>Total:</b>
<span ng-repeat="c in invoice.currencies">
{{invoice.total(c) | currency:c}}
</span><br>
<button class="btn" ng-click="invoice.pay()">Pay</button>
</div>
</div>
</body>
</html>
script files
(function(angular) {
'use strict';
angular.module('finance2', [])
.factory('currencyConverter', function() {
var currencies = ['USD', 'EUR', 'CNY'];
var usdToForeignRates = {
USD: 1,
EUR: 0.74,
CNY: 6.09
};
var convert = function(amount, inCurr, outCurr) {
return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
};
return {
currencies: currencies,
convert: convert
};
});
})(window.angular);
(function(angular) {
'use strict';
angular.module('invoice2', ['finance2'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = currencyConverter.currencies;
this.total = function total(outCurr) {
return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
};
this.pay = function pay() {
window.alert('Thanks!');
};
}]);
})(window.angular);

You have to change the
var app = angular.module('MyModule');
to
var app = angular.module('MyModule', []);
Check the []
Also
app.controller('MyController',[MyService,function MyController(MyService){
To
app.controller('MyController',["MyService",function MyController(MyService){
Check the " in MyService
Few more fixes
There are some more fixes,
You have to close the tag.
return amount*values[selCur]/values[baseCur]; <- Here changed ( to [
var convert = has to be changed to this.convert =

Please use <script></script> instead <script src="C:\Users\komar\Desktop\script.js"></script>, and copy your JavaScript between the script tag.

Find the updated code below
var app = angular.module('MyModule', []);
app.controller('MyController', ["MyService", function MyController(MyService) {
this.quantity = 1;
this.costs = 2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur) {
return MyService.currentCurrencies(this.quantity*this.costs, this.selCur, baseCur);
}
this.createAlert = function createAlert() {
window.alert('Thanks!');
};
}]);
app.factory('MyService', function() {
var currencies = ['USD', 'EUR', 'CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount, selCur, baseCur) {
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The angularjs app!</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="MyModule" ng-controller="MyController as ctrl">
<b>Invoice:</b><br>
<div>
Quantity:<input type = "number" min = 0 ng-model = "ctrl.quantity" required><br>
Costs:<input type = "number" min=0 ng-model="ctrl.costs" required>
<select ng-model="ctrl.selCur">
<option ng-repeat = "c in ctrl.currencies">{{c}}</option>
</span><br>
<b>Total:</b><span ng-repeat= "c in ctrl.currencies">
{{ctrl.convert(c) | currency:c}}
</span><br>
<button class ="btn" ng-click="ctrl.createAlert()">Pay</button>
</div>
</div>
</body>
</html>

Your HTML code is correct you just need to change the script.js file code with following code.
var app = angular.module('MyModule', []);
app.controller('MyController',['$scope','MyService',function MyController(MyService, $scope){
this.quantity = 1;
this.costs =2;
this.selCur = 'EUR';
this.currencies = MyService.currencies;
var convert = function(baseCur){
return MyService.currentCurrencies(this.quantity*this.costs,this.selCur,baseCur);
}
this.createAlert = function createAlert(){
window.alert('Thanks!');
};
}]);
app.factory('MyService',function(){
var currencies= ['USD','EUR','CNY'];
var values = {
USD: 1,
EUR: 0.88,
CNY: 6.72
};
var currentCurrencies = function(amount,selCur,baseCur){
return amount*values(selCur)/values(baseCur);
}
return {
currentCurrencies: currentCurrencies,
currencies: currencies
};
});

Related

angular js The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part

enter image description here
The ng-model name looks like 'choice.gorntu'. I want pz1, pz2 etc. to be written in ng-model part. I did not get it. My English is not very good.
html
<div ng-repeat="choice in choices">
<input type="text" -ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
css
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
Try this one
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myapp" ng-controller="control">
<div ng-repeat="choice in choices">
<input type="text" ng-model='choice.gorntu' name="{{choice.isim}}" >
</div>
<input type="button" value='add' ng-click="addNewchoice()">
</div>
<script>
var benimapp =angular.module("myapp",[]);
benimapp.controller("control",function($scope){
$scope.choices = [{id: 'txt1',isim:'monday1',gorntu:'pz1'},{id:
'txt2',isim:'monday2',gorntu:'pz2'}];
$scope.addNewchoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'txt'+newItemNo ,isim:'monday'+newItemNo, gorntu:'pz'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>
</body>
</html>

AngularJS , pushing empty element

Im quite new with angular. What am i freaky about is that following code is showing empty buttons (edit/delete) even if it looks empty (on start) :
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form ng-submit="todoAdd(item)">
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="submit" value="Add New">
</form>
<br>
<div ng-repeat="x in todoList">
<span ng-bind="x.todoText"></span><button id="#edit" ng-click="edit(item)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [{}];
$scope.todoAdd = function(item) {
$scope.todoList.push({todoText:$scope.todoInput);
$scope.todoInput = "";
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
//function
};
});
</script>
</body>
</html>
And also can somebody to help me after clicking on edit to push todoText to input and change caption of addnew to save? and afterthen change it to addNew again?
Thank you very much
Replace line
$scope.todoList = [{}];
to
$scope.todoList = [];
Then, it wouldn't show you empty line.
//Full code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form>
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="button" value="{{actionName}}" ng-click="todoAdd()" />
</form>
<br>
<div ng-repeat="x in todoList">
<span>{{x.todoText}}</span><button id="#edit" ng-click="edit(x)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [];
$scope.actionName = 'Add';
$scope.todoAdd = function() {
if($scope.actionName === 'Add'){
$scope.todoList.push({todoText:$scope.todoInput});
$scope.todoInput = "";
} else {
var index = $scope.todoList.indexOf($scope.temp);
console.log('index: ' + index);
$scope.todoList.splice(index, 1, {todoText:$scope.todoInput});
$scope.actionName = 'Add';
}
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
$scope.todoInput=item.todoText;
$scope.temp = item;
$scope.actionName = 'Save';
};
});
</script>
</body>
</html>

How do I send a div value to a function in angular controller

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span></li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
<p>{{errortext}}</p>
</div>
</body>
</html>
The line <input ng-model="addMe"> takes the input values and adds to the list
What if I want to define a <div> instead of <input> to send the value to my controller instead of <input> ? I have been trying this for long now and can not get a value enclosed between <div> and </div> sent over to the controller.
Just put your x as parameter on addToCart to add it to cart in the controller.
See demo here.

AngularJS Multiple ng-app within a page

I have just started learning Angular JS and created some basic samples however I am stuck with the following problem.
I have created 2 modules and 2 controllers.
shoppingCart -> ShoppingCartController
namesList -> NamesController
There are associated views for each controller. The first View renders fine but second is not rendering. There are no errors.
http://jsfiddle.net/ep2sQ/
Please help me solve this issue.
Also is there any possibility to add console in View to check what values are passed from Controller.
e.g. in the following div can we add console.log and output the controller values
<div ng-app="shoppingCart" ng-controller="ShoppingCartController">
</div>
So basically as mentioned by Cherniv we need to bootstrap the modules to have multiple ng-app within the same page. Many thanks for all the inputs.
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [{
product_name: "Product 1",
price: 50
}, {
product_name: "Product 2",
price: 20
}, {
product_name: "Product 3",
price: 180
}];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
angular.bootstrap(document.getElementById("App2"), ['namesList']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap()
HTML
<!-- Automatic Initialization -->
<div ng-app="myFirstModule">
...
</div>
<!-- Need To Manually Bootstrap All Other Modules -->
<div id="module2">
...
</div>
JS
angular.
bootstrap(document.getElementById("module2"), ['mySecondModule']);
The reason for this is that only one AngularJS application can be automatically bootstrapped per HTML document. The first ng-app found in the document will be used to define the root element to auto-bootstrap as an application.
In other words, while it is technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework.
You can use angular.bootstrap() directly... the problem is you lose the benefits of directives.
First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.
Secondly the association between the two is not as apparent. With ngApp you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap() could be invoked from anywhere in your code.
If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule. Here is what your code would look like using it:
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular.ng-modules.js"></script>
<script>
var moduleA = angular.module("MyModuleA", []);
moduleA.controller("MyControllerA", function($scope) {
$scope.name = "Bob A";
});
var moduleB = angular.module("MyModuleB", []);
moduleB.controller("MyControllerB", function($scope) {
$scope.name = "Steve B";
});
</script>
</head>
<body>
<div ng-modules="MyModuleA, MyModuleB">
<h1>Module A, B</h1>
<div ng-controller="MyControllerA">
{{name}}
</div>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
<div ng-module="MyModuleB">
<h1>Just Module B</h1>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
</body>
</html>
You can get the source code for it at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's implemented in the same way as ngApp. It simply calls angular.bootstrap() behind the scenes.
In my case I had to wrap the bootstrapping of my second app in angular.element(document).ready for it to work:
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("app2"), ["app2"]);
});
Here's an example of two applications in one html page and two conrollers in one application :
<div ng-app = "myapp">
<div ng-controller = "C1" id="D1">
<h2>controller 1 in app 1 <span id="titre">{{s1.title}}</span> !</h2>
</div>
<div ng-controller = "C2" id="D2">
<h2>controller 2 in app 1 <span id="titre">{{s2.valeur}}</span> !</h2>
</div>
</div>
<script>
var A1 = angular.module("myapp", [])
A1.controller("C1", function($scope) {
$scope.s1 = {};
$scope.s1.title = "Titre 1";
});
A1.controller("C2", function($scope) {
$scope.s2 = {};
$scope.s2.valeur = "Valeur 2";
});
</script>
<div ng-app="toapp" ng-controller="C1" id="App2">
<br>controller 1 in app 2
<br>First Name: <input type = "text" ng-model = "student.firstName">
<br>Last Name : <input type="text" ng-model="student.lastName">
<br>Hello : {{student.fullName()}}
<br>
</div>
<script>
var A2 = angular.module("toapp", []);
A2.controller("C1", function($scope) {
$scope.student={
firstName:"M",
lastName:"E",
fullName:function(){
var so=$scope.student;
return so.firstName+" "+so.lastName;
}
};
});
angular.bootstrap(document.getElementById("App2"), ['toapp']);
</script>
<style>
#titre{color:red;}
#D1{ background-color:gray; width:50%; height:20%;}
#D2{ background-color:yellow; width:50%; height:20%;}
input{ font-weight: bold; }
</style>
You can merge multiple modules in one rootModule , and assign that module as
ng-app to a superior element ex: body tag.
code ex:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="namesController.js"></script>
<script src="myController.js"></script>
<script>var rootApp = angular.module('rootApp', ['myApp1','myApp2'])</script>
<body ng-app="rootApp">
<div ng-app="myApp1" ng-controller="myCtrl" >
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<div ng-app="myApp2" ng-controller="namesCtrl">
<ul>
<li ng-bind="first">{{first}}
</li>
</ul>
</div>
</body>
</html>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [{
product_name: "Product 1",
price: 50
}, {
product_name: "Product 2",
price: 20
}, {
product_name: "Product 3",
price: 180
}];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
var namesModule = angular.module("namesList2", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("App2"), ['namesList']);
angular.bootstrap(document.getElementById("App3"), ['namesList2']);
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
<div id="App3" ng-app="namesList2" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
</body>
</html>
// root-app
const rootApp = angular.module('root-app', ['app1', 'app2E']);
// app1
const app11aa = angular.module('app1', []);
app11aa.controller('main', function($scope) {
$scope.msg = 'App 1';
});
// app2
const app2 = angular.module('app2E', []);
app2.controller('mainB', function($scope) {
$scope.msg = 'App 2';
});
// bootstrap
angular.bootstrap(document.querySelector('#app1a'), ['app1']);
angular.bootstrap(document.querySelector('#app2b'), ['app2E']);
<!-- angularjs#1.7.0 -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<!-- root-app -->
<div ng-app="root-app">
<!-- app1 -->
<div id="app1a">
<div ng-controller="main">
{{msg}}
</div>
</div>
<!-- app2 -->
<div id="app2b">
<div ng-controller="mainB">
{{msg}}
</div>
</div>
</div>
Only one app is automatically initialized. Others have to manually initialized as follows:
Syntax:
angular.bootstrap(element, [modules]);
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="angular.js#1.5.8"></script>
<script data-require="ui-router#0.2.18" data-semver="0.2.18" src="//cdn.rawgit.com/angular-ui/ui-router/0.2.18/release/angular-ui-router.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
var parentApp = angular.module('parentApp', [])
.controller('MainParentCtrl', function($scope) {
$scope.name = 'universe';
});
var childApp = angular.module('childApp', ['parentApp'])
.controller('MainChildCtrl', function($scope) {
$scope.name = 'world';
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('childApp'), ['childApp']);
});
</script>
</head>
<body>
<div id="childApp">
<div ng-controller="MainParentCtrl">
Hello {{name}} !
<div>
<div ng-controller="MainChildCtrl">
Hello {{name}} !
</div>
</div>
</div>
</div>
</body>
</html>
AngularJS API
You can define a Root ng-App and in this ng-App you can define multiple nd-Controler. Like this
<!DOCTYPE html>
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController1', function ($scope) {
$scope.student = {
firstName: "MUKESH",
lastName: "Paswan",
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
mainApp.controller('studentController2', function ($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Hindi', marks: 67 }
],
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
<body>
<div ng-app = "mainApp">
<div id="dv1" ng-controller = "studentController1">
Enter first name: <input type = "text" ng-model = "student.firstName"><br/><br/> Enter last name: <input type = "text" ng-model = "student.lastName"><br/>
<br/>
You are entering: {{student.fullName()}}
</div>
<div id="dv2" ng-controller = "studentController2">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
I have modified your jsfiddle, can make top most module as rootModule for rest of the modules.
Below Modifications updated on your jsfiddle.
Second Module can injected in RootModule.
In Html second defined ng-app placed inside the Root ng-app.
Updated JsFiddle:
http://jsfiddle.net/ep2sQ/1011/
Use angular.bootstrap(element, [modules], [config]) to manually start up AngularJS application (for more information, see the Bootstrap guide).
See the following example:
// root-app
const rootApp = angular.module('root-app', ['app1', 'app2']);
// app1
const app1 = angular.module('app1', []);
app1.controller('main', function($scope) {
$scope.msg = 'App 1';
});
// app2
const app2 = angular.module('app2', []);
app2.controller('main', function($scope) {
$scope.msg = 'App 2';
});
// bootstrap
angular.bootstrap(document.querySelector('#app1'), ['app1']);
angular.bootstrap(document.querySelector('#app2'), ['app2']);
<!-- angularjs#1.7.0 -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<!-- root-app -->
<div ng-app="root-app">
<!-- app1 -->
<div id="app1">
<div ng-controller="main">
{{msg}}
</div>
</div>
<!-- app2 -->
<div id="app2">
<div ng-controller="main">
{{msg}}
</div>
</div>
</div>
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="shoppingCartParentModule" >
<div ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="name in names">
<p>{{name.username}}</p>
</div>
</div>
</div>
</body>
<script>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [
{product_name: "Product 1", price: 50},
{product_name: "Product 2", price: 20},
{product_name: "Product 3", price: 180}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [
{username: "Nitin"},
{username: "Mukesh"}
];
}
);
angular.module("shoppingCartParentModule",["shoppingCart","namesList"])
</script>
</html>

broadcasting model changes

I'm trying to set up a little POC to see whether or not angular would work for something I'm in the middle of.
I set up a REST server which I am able to CRUD with via angular. However, as the documentation and tutorials out there are so all over the place (read: SUPER inconsistent), I am not sure that the behavior I'm not seeing is the result of incorrect code or it's not something I can do like this.
I've gleaned from the docs that two-way binding is available, but it isn't clear how it works. NB I've read dozens of articles explaining how it works at a low level a'la https://stackoverflow.com/a/9693933/2044377 but haven't been able to answer my own question.
I have angular speaking to a REST service which modifies a sql db.
What I am wondering about and am trying to POC is if I have 2 browsers open and I change a value in the db, will it reflect in the other browser window?
As I said, I have it updating the db, but as of now it is not updating the other browser window.
app.js
angular.module('myApp', ['ngResource']);
var appMock = angular.module('appMock', ['myApp', 'ngMockE2E']);
appMock.run(function($httpBackend) {});
controllers.js
function MainCtrl($scope, $http, $resource) {
$scope.message = "";
$scope.fruits = [];
$scope.fruit = {};
$scope.view = 'partials/list.html';
var _URL_ = '/cirest/index.php/rest/fruit';
function _use_$resources_() { return false; }
function _fn_error(err) {
$scope.message = err;
}
$scope.listFruits = function() {
$scope.view = 'partials/list.html';
var fn_success = function(data) {
$scope.fruits = data;
};
$http.get(_URL_).success(fn_success).error(_fn_error);
}
function _fn_success_put_post(data) {
$scope.fruit = {};
$scope.listFruits();
}
function createFruit() {
$http.post(_URL_, $scope.fruit).success(function(data){
$scope.listFruits()
}).error(_fn_error);
}
function updateFruit() {
$http.post(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
function deleteFruit() {
$http.put(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
$scope.delete = function(id) {
if (!confirm("Are you sure you want do delete the fruit?")) return;
$http.delete("/cirest/index.php/rest/fruit?id=" + id).success(_fn_success_put_post).error(_fn_error);
}
$scope.newFruit = function() {
$scope.fruit = {};
$scope.fruitOperation = "New fruit";
$scope.buttonLabel = "Create";
$scope.view = "partials/form.html";
}
$scope.edit = function(id) {
$scope.fruitOperation = "Modify fruit";
$scope.buttonLabel = "Save";
$scope.message = "";
var fn_success = function(data) {
$scope.fruit = {};
$scope.fruit.id = id;
$scope.view = 'partials/form.html';
};
$http.get(_URL_ + '/' + id).success(fn_success).error(_fn_error);
}
$scope.save = function() {
if ($scope.fruit.id) {
updateFruit();
}
else {
createFruit();
}
}
$scope.cancel = function() {
$scope.message = "";
$scope.fruit = {};
$scope.fruits = [];
$scope.listFruits();
}
$scope.listFruits();
}
MainCtrl.$inject = ['$scope', '$http', '$resource'];
list.html
{{message}}
<hr/>
New Fruit
<ul ng-model="listFruit">
<li ng-repeat="fruit in fruits">
id [{{fruit.id}}] {{fruit.name}} is {{fruit.color}}
[X]
</li>
</ul>
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>FRUUUUUUUUUUUUUUUUUUUUUUUUUUUIT</title>
<link rel="stylesheet" href="css/bootstrap/css/bootstrap.css"/>
</head>
<body>
<div class="navbar">NAVBARRRRRRRRRRR</div>
<div class="container">
<div class="row">
<div ng-controller="MainCtrl">
<button ng-click="listFruits()">ListFruit()</button>
<button ng-click="cancel()">Cancel()</button>
<ng-include src="view"></ng-include>
</div>
</div>
</div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
form.html
<h3>{{fruitOperation}}</h3>
<hr/>
<form name="fruitForm">
<input type="hidden" name="" ng-model="fruit.id" />
<p><label>name</label><input type="text" name="name" ng-model="fruit.name" value="dfgdfgdfg" required="true" /></p>
<p><label>color</label><input type="text" name="color" ng-model="fruit.color" value="fruit.color" required="true" /></p>
<hr/>
<input type="submit" ng-click="save()" value="{{buttonLabel}}" /> <button ng-click="cancel()">Cancel</button>
</form>
Thanks for any insight or pointers.
Two-way binding refers to changes occurring in your controller's scope showing up in your views and vice-versa. Angular does not have any implicit knowledge of your server-side data. In order for your changes to show up in another open browser window, for example, you will need to have a notification layer which pushes changes to the client via long polling, web sockets, etc.

Resources