I am new to AngularJS JavaScript. Just started learning it. I was trying with some small sample programs. Here is what I tried but its throwing error.
<body ng-app="myApp">
<div ng-controller="myCtrl">
{{time}}
<br>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.service('hexafy', ['',
function() {
this.myfunc = function(num) {
return num.toString(16);
}
}
]);
app.controller('myCtrl', ['hexafy', '$scope', '$interval',
function(hexafy, $scope, $interval) {
$scope.time = new Date().toLocaleTimeString();
$interval(function() {
$scope.time = new Date().toLocaleTimeString();
}, 1000);
// $scope.hex = hexafy.myfunc(255);
}
]);
</script>
The array syntax is used when the code is minified and keep the mapping of arguments. For more on this please see my other answer Why we Inject our dependencies two times in angularjs?.
In the code, as there is no parameter passed to the hexafy service, there is no need of using the array syntax and pass empty string.
app.service('hexafy', ['',
function() {
Use normal syntax.
app.service('hexafy', function() { // <-- Remove `[` and empty string from here
...
...
}); // <-- Remove `]` from here
var app = angular.module("myApp", []);
app.service('hexafy', function() {
this.myfunc = function(num) {
return num.toString(16);
}
});
app.controller('myCtrl', ['hexafy', '$scope', '$interval',
function(hexafy, $scope, $interval) {
$scope.time = new Date().toLocaleTimeString();
$interval(function() {
$scope.time = new Date().toLocaleTimeString();
}, 1000);
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
{{ time }}
<br />
</div>
</body>
What Tushar has suggested is perfect, Just adding working piece of Plunker
app.service('hexafy',function() {
this.myfunc = function(num) {
return num.toString(16);
}
}
);
Related
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+.
I'm able to get seconds in Time using AngularJS and its "Interval" option but i was thing about adding milliseconds to the same with 2 digits. Below is the code. can anyone tell me on how to add milliseconds to it.
AngularJs Code
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
HTML
<div class="col-lg-2" ng-app="myApp" ng-controller="myCtrl">
<h3 style="color: blue;font-family: cursive;"><b>{{theTime}}</b></h3>
</div>
Update - On how i found the solution.
I just did the following changes. Thanks to Pranjal
AngularJS Code
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date();
$interval(function () {
$scope.theTime = new Date();
}, 1);
});
HTML
<div class="col-lg-2" ng-app="myApp" ng-controller="myCtrl">
<h3 style="color: blue;font-family: cursive;font-size: 20;margin-left: 20;"><b>{{theTime | date:'HH:mm:ss:sss a'}}</b></h3>
</div>
<body>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.CurrentDate = new Date();
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<span>{{CurrentDate | date:'HH:mm:ss:sss'}}</span>
</div>
</body>
<!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'm doing the tutorial about angularjs. Everything is fine until working with route.
I 'm search about this problem before, but it not working for me.
I'm doing exactly the code which author type but it's not working.
ng-view put in index.html
<html ng-app="githubViewer">
<head>
<title>Demo</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="MainController.js"></script>
<script type="text/javascript" src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view=""></div>
</body>
app.js
(function() {
var app = angular.module("githubViewer", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo:"/main"});
});})();
MainController.js
(function() {
var app = angular.module("githubViewer");
var MainController = function(
$scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, 5, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = "angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);})();
main.html
<div>
{{countdown}}
{{username}}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="usẻname to ind" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)">
</form>
github.js
(function() {
var github = function($http) {
var getUser = function(username){
return $http.get("https://api.github.com/users/" + username)
.then(function(response){
return response.data;
});
};
var getRepos = function(user){
return $http.get(user.repos_url)
.then(function(response){
return response.data;
});
};
return{
getUser : getUser,
getRepos: getRepos
};
};
var module = angular.module("githubViewer");
module.factory("github", github);})();
You have an error in your code:
var MainController = function($scope, $interval, , $location) {
// unnecessary comma here ----^
Remove comma (or insert missing parameter) and your app should start working.
In general I recommend to keep developer console open all the time during coding.
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.