$compile not triggering ng-click in angularjs - html

I am generating dynamic html element from angularjs controller.I have used $compile
to make ng-click work inside html element.But still it is not calling the function.
Here is my js
var accountApp = angular.module('accountApp', ['ngRoute']);
accountApp.config(['$compileProvider',function($compileProvider )
.controller('myController',function($scope,$compile)
{
var searchHTML = '<li><a href="javascript:void(0)" data-ng-
click="setMarkerToCenterA()">'+item.title+'</a></li>';
$compile(searchHTML)($scope);
$scope.setMarkerToCenterA = function() {
alert("this alert is not calling");
}
});
}]);
I have injected the dependencies also.Can anyone tell why ng-click is not calling function even though i am using $compile?

First you need an element where this li element will be located.
<div ng-controller="myController">
<ul id="list"></ul>
</div>
Then in your controller:
var element = angular.element("#list");
element.html($compile(html)($scope));
$scope.setMarkerToCenterA = function() {
alert("Here");
};

Probably you missed to parse the HTML string using angular.element(htmlString) which is then compiled.
var app = angular.module('stackoverflow', []);
app.controller('MainCtrl', function($scope, $compile, $sce) {
var searchHTML = 'hello';
var template = angular.element(searchHTML);
$compile(template)($scope);
angular.element(document.querySelector('#container')).append(template);
$scope.setMarkerToCenterA = function() {
alert("this alert is now calling");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="stackoverflow" ng-controller="MainCtrl">
<div id="container"></div>
</div>

Related

Trying to import data from JSON file, and displaying in HTML

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.

Angular service not storing data between two controllers

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.

Displaying html via angular

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

Adding an angularJS directive based on a parameter value

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

Angular - append html through different frames with one module per frame

My code have the main windonw and one iframe and each one with your module. A button in main window fires click event that should append html into iframe, the new html when appended into that should apply interceptors and directives properly, but it doesn't work!
Angular javascript:
angular.module('module1',[]).controller('Controller1', function ($scope) {
$scope.get = function(){
$http.jsonp("some_url_here").success(function(html){
$scope.content = html;
});
}
}).directive('click', function($compile) {
return {
link: function link(scope, element, attrs) {
element.bind('click',function(){
var unbind = scope.$watch(scope.content, function() {
var div=document.getElementById("frame").contentWindow.angular.element("divId");
div.append($compile(scope.content)(div.scope()));
unbind();
});
});
}
}
});
angular.module('module2',[]).directive('a', function() {
return {
restrict:'E',
link: function(scope, element, attrs) {
console.log('ping!');
console.log(attrs.href);
}
};
});
Html code:
<html ng-app="modile1">
<div ng-controller="Controller1">
<button type="button", ng-click="get('any_value')", click:""/> Load frame
</div>
<iframe id="frame" src="/please/ignore/this">
<!-- considere the html as appended from iframe-src and contains ng-app="module2" -->
<html ng-app="module2">
<div id="divId">
<!-- code should be inject here -->
</div>
</html>
</iframe>
</html>
Please, considere that angularjs, jquery if applicable, modules-declaration as well as headers are loaded properly.
I'd like to load the html content from main-frame/window into iframe and run interceptors and directives properly. Is it possible? If yes, how can I do it?
Thanks for advancing!
I've tried this code and it seems work fine! I found it here: http://www.snip2code.com/Snippet/50430/Angular-Bootstrap
var $rootElement = angular.element(document.getElementById("frame").contentWindow.document);
var modules = [
'ng',
'module2',
function($provide) {
$provide.value('$rootElement', $rootElement)
}
];
var $injector = angular.injector(modules);
var $compile = $injector.get('$compile');
$rootElement.find("div#divId").append(scope.content);
var compositeLinkFn = $compile($rootElement);
var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);
$rootScope.$apply();