Here's the script I'm using :
(function() {
var app = angular.module("myQuiz", []);
app.controller('QuizController', ['$scope', '$http', '$sce', function($scope, $http, $sce){
$scope.score = 0;
$scope.activeQuestion = -1;
$scope.activeQuestionAnswered = 0;
$scope.percentage = 0;
$http.get('quiz_data.json').then(function(quizData){
$scope.myQuestions = quizData.data;
$scope.totalQuestions = $scope.myQuestions.length;
});
}])
})
After this, I'm trying to display the 'total questions' on my HTML using {{totalQuestions}} but instead of showing the number of questions, it just displays {{totalQuestions}} as it is.
You have this in code:
(function() {
var app = angular.module("myQuiz", []);
// ..
})
But this will never actually execute the function, so your module won't be defined.
Just add the () at the end:
(function() {
var app = angular.module("myQuiz", []);
// ..
}())
Try renaming <div id="myQuiz"> to something else it can not be same as ng-app="myQuiz" and define your scope variable inside <div id="myQuizId" ng-controller = 'QuizController'> {{hereYourVariable}} </div>
Add these things in your index.html file :
ng-app = "myQuiz",
ng-controller="QuizController" if required,
add reference to your angular js cdn or its script file
then below angular cdn/script reference add your script file reference.
Related
I want to display the current system time in the page i am making but it seems to be not working. i dont know why
<script src="angular/angular.min.js"></script>
<script src="css/bootstrap.min.js"></script>
<script src="css/jquery.min.js"></script>
<script src="angular/angular-ui.js"></script>
another code
<script type="text/javascript">
var mymodal = angular.module('mymodal', [])
app.controller('MyController', function ($scope, $filter) {
var date = new Date();
$scope.ddMMyyyy = $filter('date')(new Date(), 'dd/MM/yyyy');
});
</script>
<div ng-app="mymodal" ng-controller="MyController">
<u>dd/MM/yyyy format</u><br /><span ng-bind = "ddMMyyyy"></span>
</div>
Modify your code as given and include HH:mm:ss for time.
var mymodal = angular.module('mymodal', [])
mymodal.controller('MyController', function ($scope, $filter) {
var date = new Date();
$scope.ddMMyyyy = $filter('date')(new Date(), 'dd/MM/yyyy HH:mm:ss');
});
As mentioned by #AnikIslamAbhi, there are two issues that need to be addressed.
app should be mymodal instead
put jquery before angular
After updating your code, it works correctly.
See JSFiddle
Update
However, a better practice is to not assign Angular module to a variable. Instead, use angular.module() to get a module.
// This declares a module (note the second parameter)
angular.module('MyModule', []);
// This retrieves a module
angular
.module('MyModule')
.controller('MyController', function() {});
// Module declaration can be chained with controllers, filters, etc.
angular
.module('AnotherModule', [])
.controller('AnotherController', function() {})
.filter('AnotherFilter', function() {});
Checkout the developer guide on modules.
I am trying to use a service to set title in controller1 and then access title in controller2.
sharedProperties.setTitle(title) works in controller1, but when I try to get the title in controller2, it gets "title" (the initial value) instead of the new value.
I've also tried storing title in an object but it didn't work.
app.service('sharedProperties', function () {
var title = "title"
return {
getTitle: function () {
return title;
},
setTitle: function (val) {
title = val;
}
}
});
app.controller('controller1', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
sharedProperties.setTitle(title);
});
}]);
app.controller('controller2', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$scope.sharedTitle = function() {
return sharedProperties.getTitle();
};
}]);
And in my view, I have {{ sharedTitle() }} which should, as I understand it, update the title text with the new title.
Also, in case this is relevant: the two controllers are linked to two different html pages.
What am I doing wrong?
EDIT
Updated button listener:
$('body').on("click", "button[name=btnListItem]", function () {
// gets the text of the button (title)
var title = $(this).text();
sharedTitle(title);
alert(sharedProperties.getTitle());
document.location.href = '/nextscreen.html';
});
$scope.sharedTitle = function (title) {
sharedProperties.setTitle(title);
};
It seems to be correct in your sample code. I setup jsfiddle and it seems work correctly. Finding out a difference between my jsfiddle and your actual code would help you to find the problem you should solve.
Javascript:
angular.module('testapp', [])
.service('sharedProperties', function(){
var title = 'title';
return {
getTitle: function(){
return title;
},
setTitle: function(val){
title = val;
}
};
})
.controller('controller1', function($scope, sharedProperties){
$scope.change_title = function(newvalue){
sharedProperties.setTitle(newvalue);
};
})
.controller('controller2', function($scope, sharedProperties){
$scope.sharedTitle = function(){
return sharedProperties.getTitle();
};
})
Html:
<div ng-app="testapp">
<div ng-controller="controller1">
<input ng-model="newvalue">
<button ng-click="change_title(newvalue)">Change Title</button>
</div>
<div ng-controller="controller2">
<span>{{sharedTitle()}}</span>
</div>
</div>
My jsfiddle is here.
You have to print console.log(sharedProperties.getTitle()); Dont need return from controller.
So your code of controller2 is $scope.sharedTitle = sharedProperties.getTitle();
You need to use the $apply so that angular can process changes made outside of the angular context (in this case changes made by jQuery).
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
$scope.$apply(function() {
sharedProperties.setTitle(title);
});
});
See plunker
That said, this is BAD PRACTICE because you're going against what angular is meant for. Check “Thinking in AngularJS” if I have a jQuery background?. There are cases when you need to use $apply like when integrating third party plugins but this is not one of those cases.
I'm trying to show the html that has been encoded. but this doesn't seem to work.
input is via:
<h1>Some header</h1>
and it shows:
<h1>Some header</h1>
But I want it to render the html; but as shown in the following pen; it just show the source html
this is my current controller:
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('myCtrl', function ($scope, $sce) {
$scope.trustedHtml = $sce.trustAsHtml('<h1>Some header</h1>');
});
with the following html:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-bind-html="trustedHtml"></div>
</div>
http://codepen.io/cskiwi/pen/PqXdOa
To decode the html, you can use this trick:
var encodedHtml = '<h1>Some header</h1>';
var decodedHtml = angular.element('<div>').html(encodedHtml).text();
Then apply to your property:
$scope.trustedHtml = $sce.trustAsHtml(decodedHtml);
You will have to sanitize your html data/string :
I have the same problem before some time , then i created a filter for this problem, You can use this filter to do sanitize your html code:
app.filter("sanitize", ['$sce', function($sce) {
return function(htmlCode) {
return $sce.trustAsHtml(htmlCode);
}
}]);
in html you can use like this:
<div ng-bind-html="businesses.oldTimings | sanitize"></div>
businesses.oldTimings is $scope variable having description of strings or having strings with html tags , $scope.businesses.oldTimings is the part of particular controller that you are using for that html.
see in the snapshot:
you can use limitHtml filter to do the same:
app.filter('limitHtml', function() {
return function(text, limit) {
var changedString = String(text).replace(/<[^>]+>/gm, ' ');
var length = changedString.length;
return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString;
}
});
Then you can add bothe filter in your html like that:
<p class="first-free-para" ng-bind-html="special.description| limitHtml : special.description.length | sanitize">
Hope it will work for you.
Check this codepen please
http://codepen.io/anon/pen/xGmaWR
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-bind-html="trustedHtml"></div>
</div>
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('myCtrl', function ($scope) {
$scope.trustedHtml = '<h1>Some header</h1>';
});
Angular Docs
TL;DR: Is there a way to dynamically set a directive based on a parameter value? Something similar to ng-class for setting css elements, but a way to set the directive based on the value in the scope. I would have the value in the scope so I could call:
<div class="data.directiveType"></div>
When
data.directiveType = "my-directive"
the div would become
<div class="my-directive"></div>
and myDirective would be invoked?
Detailed Question:
What I am trying to do is allow the user to add elements to the web application and I wanted the directive for each element to be added based on what the user clicks.
I have the following Directives:
app.directive("mySuperman", function(){
//directive logic
});
app.directive("myBatman", function(){
//directive logic
});
app.directive("myWonderWoman", function(){
//directive logic
});
I have the following controller
app.controller("ParentCtrl", function($scope){
$scope.superHeros = [];
var superman = {directiveType: "my-superman"};
var batman = {directiveType: "my-batman"};
var wonderWoman = {directiveType: "my-wonder-woman"}
$scope.addBatman = function()
{
var batmanInstance = {}
angular.copy(batman, batmanInstance);
$scope.superHeros.push(batmanInstance);
}
$scope.addSuperman = function()
{
var supermanInstance = {}
angular.copy(superman, supermanInstance);
$scope.superHeros.push(supermanInstance);
}
$scope.addWonderWoman = function()
{
var wonderwomanInstance = {}
angular.copy(wonderWoman, wonderwomanInstance);
$scope.superHeros.push(wonderwomanInstance);
}
});
In the index.html I have
<body ng-controller="ParentCtrl>
<a ng-click="addBatman()">Add Batman</a>
<a ng-click="addSuperman()">Add Superman</a>
<a ng-click="addWonderWoman()">Add WonderWoman</a>
<div ng-repeat="hero in superHeros">
<!-- The following doesn't work, but it is the functionality I am trying to achieve -->
<div class={{hero.directiveType}}></div>
<div>
</body>
The other way I thought of doing this was just using ng-include in the ng-repeat and adding the template url to the hero object instead of the directive type, but I was hoping there was a cleaner way that I could make better use of the data binding and not have to call ng-include just to call another directive.
You can create a directive that takes the directive to add as a parameter, adds it to the element and compiles it. Then use it like this:
<div ng-repeat="hero in superHeros">
<div add-directive="hero.directiveType"></div>
</div>
Here is a basic example:
app.directive('addDirective', function($parse, $compile) {
return {
compile: function compile(tElement, tAttrs) {
var directiveGetter = $parse(tAttrs.addDirective);
return function postLink(scope, element) {
element.removeAttr('add-directive');
var directive = directiveGetter(scope);
element.attr(directive, '');
$compile(element)(scope);
};
}
};
});
Demo: http://plnkr.co/edit/N4WMe8IEg3LVxYkdjgAu?p=preview
I would like to update some fields when I receive a geoposition for a give user.
Until know I have the following code:
http://jsfiddle.net/VSph2/10/
Firstly, I get a Error: Unknown provider: positionProvider <- position (only on jsfiddle). I do not get this error on my real site.
The problem is that when I get the position I update the position object in the service but it does not update in the HTML view.
Any suggestions?
Try this. Fiddle
var test = angular.module('myApp', []);
var services = angular.module('myApp.services', []);
services.factory('position', ['$http', function ($http) { ...
should be
var test = angular.module('myApp', []);
test.factory('position', ['$http', function ($http) { ...
You should update the controller code as this, to use a callback function and $apply to apply the value set to the scope.
position.getPosition(function (p) {
$scope.$apply(function () {
$scope.position.latitude = p.coords.latitude;
$scope.position.longitude = p.coords.longitude;
$scope.position.accuracy = p.coords.accuracy;
});
});