This is an AngularJS inheritance code where the inheritance is applied in the functions but there is no output coming for this code.
custDetails and empPaycheck are the two functions where inheritance is applied but the code has some error which I am not been able to find.
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Controller Inheritance</title>
<script src="angulaar.min.js"></script>
<script>
var app = angular.module("sample",
[]).run(["$rootScope",function($rootScope){
$rootScope.taxPe`enter code here`rcent = 30;
}]);
app.controller("custDetails", ["$scope",function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}]);
</script>
</head>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong>
Department.
<div controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
</html>
You should use $scope.$parent to access parent $scope variables in a child controller.
Also in your HTML code there's a typo where controller should be ng-controller.
Look at the following working example.
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.$parent.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.$parent.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div>
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
There is error in your module run block near $rootScope.taxPe;
You are using controller attribute instead of ng-controller.
Here is a working code snippet:
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
P.S.: Personally I would not recommend using $rootScope and scope inheritance, you can use services to share data between controllers. Also would suggest you looking into component API that comes in v1.5+.
Related
I'm new to AngularJS. I was trying to find the center point on the page with JavaScript then bind it to the $scope object. I'm not entirely sure if I bound the JavaScript variables correctly. After I did that, I was trying to preview the values in my HTML page. When I ran the code it threw an error message.
<script type="text/javascript">
var Page_Center_Width = $(window).width() / 2;
var Page_Center_Height = $(window).height() / 2;
</script>
<script>
var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($scope, $interval, $window) {
$scope.Window_Width = $window.Page_Center_Width;
$scope.Window_Height = $window.Page_Center_Height;
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl" >
<div >Window-Width: {{Window_Width}}</div>
<div >Window-Height: {{Window_Height}}</div>
</div>
var Page_Center_Width = $(window).width() / 2;
var Page_Center_Height = $(window).height() / 2;
var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($scope, $interval, $window) {
$scope.Window_Width = $window.Page_Center_Width;
$scope.Window_Height = $window.Page_Center_Height;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<div>Window-Width: {{Window_Width}}</div>
<div>Window-Height: {{Window_Height}}</div>
</div>
You have different problem at your snippet. You put script tag on javascript section.
var app = angular.module('myApp', []);
app.controller('mainCtrl', function($scope, $interval, $window) {
$scope.Window_Width = $window.Page_Center_Width;
$scope.Window_Height = $window.Page_Center_Height;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<div>Window-Width: {{Window_Width}}</div>
<div>Window-Height: {{Window_Height}}</div>
</div>
<script type="text/javascript">
var Page_Center_Width = 3434;
var Page_Center_Height = 1222;
</script>
Angular expressions on one of my view are rendering same data on screen
it would show : hello - hello ( for different expressions {{a}}, {{b}} )
There is cleary different data binded to 'a' and 'b' variables in controller.
html view :
{{ a | json }} - {{ b | json }}
angular controller:
app.controller('myctrl', function($scope, myservice) {
var self = this;
self.getA = function() {
$scope.a = 'hello';
}
self.getB = function() {
$scope.b = 'hey';
}
self.getA(); //call on controller startup
self.getB();
});
Your code works without any issue,
Make sure you are doing the following.
DEMO
var app = angular.module('myctrl',[]);
app.controller('myctrl', function($scope) {
var self = this;
self.getA = function() {
$scope.a = 'hello';
}
self.getB = function() {
$scope.b = 'hey';
}
self.getA(); //call on controller startup
self.getB();
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dashboard</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body >
<div ng-app="myctrl" >
<div ng-controller="myctrl as ctrl" >
{{ a }} - {{ b }}
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="keyboard.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab|Roboto' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="keyboard.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-include src="'keyboard.html'"></div>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
</script>
</body>
</html>
I know this is a bit thrown together, (the main code is just an example app from w3schools) but it shows what I am trying to do. So I have a keyboard app that I am bringing into the file (ng-include) and it appears absolutely wonderfully. My issue is that $scope is not being recognized. I have read the "Understanding Scopes" github document but it is just a bit much for me to take in. If someone could explain what I need to do to make sure that all of my $scope functions actually function, I would appreciate it greatly.
as Fissio said in the comments, you have a scope function declared outside of your controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
/**** see this here ****/
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
this is what you need:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
});
you can't use the keyword $scope outside of your controller because its bound to your controller. When it's outside angular will not know what it is that's why it will say something like it's not recognized
I want to broadcast angular event from javascript function i.e angular.injector(['ng', 'myModule']).get("mySharedService").prepForBroadcast('hello');
By using above line I can invoke prepForBroadcast() but I can't catch event in $scope.$on()
Note: I want to call prepForBroadcast() method from javascript function.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- SPELLS -->
<!-- load angular via CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
<style>
.question{
border:1px solid darkgray;
padding:10px;
margin-bottom:10px;
}
</style>
</head>
<body>
<div ng-app="myModule">
<div id="appID" ng-controller="ControllerZero">
<input ng-model="message" >
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
<my-component ng-model="message"></my-component>
</div>
</body>
<script>
angular.injector(['ng','myModule']).get("mySharedService").prepForBroadcast('hello');
</script>
</html>
script.js file
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
console.log('prepForBroadcast');
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
console.log('broadcastItem');
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
controller: function($scope, $attrs, mySharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'Directive: ' + mySharedService.message;
});
},
replace: true,
template: '<input>'
};
});
function ControllerZero($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
console.log('handle event');
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];
angular.injector() creates a new injector, and with it a new $rootScope. The event will be broadcasted on this new $rootScope instead of on the one your controllers are listening on.
You need to retrieve the injector already associated with your application:
angular.element(domElement).injector();
You also need to manually trigger the digest loop for the data bindings to update, for example by using $apply.
Example:
angular.element(document).ready(function() {
var element = angular.element(document.querySelector('.ng-scope'));
var injector = element.injector();
var scope = element.scope();
scope.$apply(function() {
injector.get('mySharedService').prepForBroadcast('hello');
});
});
Demo: http://plnkr.co/edit/NDKBdzSmvN1xY7alafir?p=preview
Another way of publishing events from one controller and listening them in other controllers would be to use angular-PubSub module.
The PubSub makes only subscribers to listen to the published events unlike the $rootScope.$broadcast in which it sends event to all the Scopes in Scope hierarchy making it inefficient as compared to the PubSub approach.
I am trying to use my scope values in my head title tag. This is external to the body element that has my controller. IS there a way to do this?
Here is my HTML:
<!DOCTYPE html>
<html ng-app="soCLean">
<head>
<title>{{locale}} {{type}} {{service}}</title>
</head>
<body ng-controller="soCleanLandingPage">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script>
var soClean = angular.module('soClean', []);
soClean.controller('soCleanLandingPage', ['$scope', function ($scope) {
$scope.locale = 'vancouver';
$scope.type = 'residential';
$scope.service = 'pressure washing';
$scope.serviceSingle = 'pressure wash';
}]);
</script>
</body>
</html>
Thanks for your help.
Just move your ng-controller to the html element.
http://plnkr.co/edit/xImv48BvoW2Y9Ibb9JTq?p=preview
(You can see the values in head in the debugger)
<!DOCTYPE html>
<html ng-app="soClean" ng-controller="soCleanLandingPage">
<head>
<title>{{locale}} {{type}} {{service}}</title>
</head>
<body >
<div>
<p>{{locale}}</p>
<p>{{type}}</p>
<p>{{service}}</p>
<p>{{serviceSingle}}</p>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script>
var soClean = angular.module('soClean', []);
soClean.controller('soCleanLandingPage', ['$scope', function ($scope) {
$scope.locale = 'vancouver';
$scope.type = 'residential';
$scope.service = 'pressure washing';
$scope.serviceSingle = 'pressure wash';
}]);
</script>
</body>
</html>
You can use the $rootScope:
app.run(function($rootScope){
$rootScope.locale = "en";
$rootScope.type = "something";
$rootScope.service = "another";
});
You can also use a fancy directive:
app.directive('title', function(){
return {
restrict: 'E',
scope:{},
template: "{{locale}} {{type}} {{service}}",
link: function(scope){
scope.locale = "en";
scope.type = "something";
scope.service = "another";
}
}
});
Check this plunker: http://plnkr.co/edit/JRblEkKaOCLNC2O7r9s4?p=preview