How to write an efficient code div.innerHTML like code in AngularJS - angularjs

If i need to change a small html dynamically on or before a success or error callback of ajax in html I do
document.getElementById("xyz").innerHTML("<img />");
in jQuery also i can do
jQuery("#xyz").html("<img />");
now I can also use handlebars for doing more complex html and attaching it in the above code.
So how can I do the above such things in Angular.js
Please give some examples of some helpful pointers

using ng-bind-html like this,
html:
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-bind-html="myText"></p>
</div>
js:
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
$scope.myText = "<img />";
});

Related

Adding angular code in script section is not working in jsfiddle

Add the following code in html box and it will work as it should be
<div ng-app="myapp" data-ng-controller='Ctrl'>
<h1> Header </h1>
<h3> {{test}} </h3>
</div>
<script>
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope){
$scope.test = "Hello";
});
</script>
Now move the JavaScript to JavaScript box
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope){
$scope.test = "Hello";
});
It start giving error: Uncaught Error: No module: myapp
I don't want to write everything in html section, any fix?
While I was playing with setting, found the answer :)
Change the setting Load Type from "OnLoad" to "No wrap - in ", see the attached image.
Strange but it is working like charm :)

VM73:49Uncaught ReferenceError: angular is not defined in jsfiddle

I am trying to run an angularJS example in jsfiddle (ofcourse learning purpose) getting below errors in console.
When I add this cdn for angular compatibility:
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js
I seen below error.
VM141 angular.min.js:6 Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=myApp&p1=Error%3A%2…oudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.5.6%2Fangular.min.js%3A21%3A19)
When I remove the external source, seen below error:
VM93:45 Uncaught ReferenceError: angular is not defined
Concern:
Do I need to add external source for angular example? If yes then what will be the correct way to add external resource. (like, search a cdn for that api and add).
Here's the code snippet:
html:
<div ng-app="myApp" ng-controller="myCtrl">
Your name: <input type="text" ng-model="name" ng-click="displayName();">
Hello {{$scope.name}}
</div>
js:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
$scope.displayName = function(){
alert("In right place");
$scope.name = "Name";
}
});
Here's the fiddle: https://jsfiddle.net/supdas87/my1juu4e/2/
I've added angular-1.0.1.js file to external resources (you just have to copy and paste the URL), and changed {{$scope.name}} by {{name}} on your HTML file. You do not have to write $scope when you use {{ }}, it is implicit.
Here is a working Fiddle based on the code you provided.
PS: I've added Angular 1.0.1, but of course you can use the version of Angular you want. You can see allreleases here.
HTML
<div ng-app="myApp" ng-controller="myCtrl">
Your name: <input type="text" ng-model="name" ng-click="displayName();">
Hello {{name}}
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.displayName = function(){
alert("In right place");
$scope.name = "Name";
}
});

nicEdit doesn't work in templates

I'm trying to add the wysiwyg nicEdit text editor to my text areas. When I goto the actual templateUrl the textbox and tool bar do work but they do not submit correctly (to my firebase db). When I goto the page that is to render the template I am unable to get get nicEdit toolbar features and just get a regular text area box. I'm using angularjs and have the templateurl as addPost.html.
So again the template does render when I goto #/addPost but not with the working nicEdit features, yet going directly to the template url addPost.html does have the nicEdit features working but then won't submit to my firebase db. Anyone have an idea on why this is so? Thanks.
Template file addPost.html:
<head>
<script type="text/javascript" language="javascript" src="../nicEdit.js"></script>
<script type="text/javascript" language="javascript">
bkLib.onDomLoaded(nicEditors.allTextAreas);
</script>
<!-- Bootstrap core CSS -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<nav class="blog-nav">
<a class="blog-nav-item " href="#/welcome">Home</a>
<a class="blog-nav-item active" href="#/addPost">Add Post</a>
<a class="blog-nav-item " style="cursor:pointer;" ng-click="logout();">Logout</a>
</nav>
</head>
<body ng-controller="AddPostCtrl">
<div class="container" >
<form class="form-horizontal" ng-submit="AddPost()">
<fieldset>
<!-- Form Name -->
<legend>Create Post</legend>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost" ></textarea>
</div>
</div>
</fieldset>
</form>
</div><!-- /.container -->
</body>
addPost.js
'use strict';
angular.module('myApp.addPost', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/addPost', {
templateUrl: 'addPost/addPost.html',
controller: 'AddPostCtrl'
});
}])
.controller('AddPostCtrl', ['$scope','$firebase','$location','CommonProp',function($scope,$firebase, $location,CommonProp) {
if(!CommonProp.getUser()){
$location.path('/main');
}
$scope.logout = function(){
CommonProp.logoutUser();
}
$scope.AddPost = function(){
var title = $scope.article.title;
var date = $scope.article.date;
var post = $scope.article.post;
var firebaseObj = new Firebase("http://..");
var fb = $firebase(firebaseObj);
fb.$push({ title: title, date: date, post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
}
}]);
Going to #addPost shows the template with out nicEdit working
But going to the actual templateUrl addPost.html it works fine, minus not being able to submit
The problem has to do with trying to run scripts Angular html partials. The simple solution is to move the scripts you need to the head of your main index file, outside of ng-view, though it does seem (according to other stackoverflow posts) technically possibly to try to get these scripts to execute:
"AngularJS: How to make angular load script inside ng-include?"
https://stackoverflow.com/a/19715343/1078450
(Also, you have html in your head file that is not likely to be rendered: <nav class="blog-nav">)
Well, I have had the same problem, with initialisation of NicEdit in templates.
First I used onDomLoaded() else, but it's better to wait for the document. With jQuery I use document.ready.
Take a look here, pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The problem is to tell NicEditor the new textarea.
Here a code sample to do this in jQuery.
var idnr = 0;
var NicEditor = new nicEditor();
$('#add').click(function(){
var $clone = $('#dummy').clone();
var id = 't_' + idnr;
idnr = idnr + 1;
$clone.attr('id',id).attr('name',id).removeClass('dummy');
$('#wrapper').append($clone);
NicEditor.panelInstance(id);
$(nicEditors.findEditor(id).elm).focus();
});
And here is a working Example of dynamic NicEdit use.

Why doesn't HTML render when passed from AngularJS?

I'd like to pass HTML back to the webpage but it is coming through as literal. Any ideas what I'm doing wrong?
HTML:
<div ng-app="app" ng-controller="ctrl">
{{price}}
<br>
Only <strike>$49</strike> $29
</div>
Angular:
var app = angular.module('app',[]);
app.controller('ctrl', function($scope,$sce){
$scope.price = $sce.trustAsHtml('Only <strike>$'+49+'</strike> $'+29);;
});
Output:
Only <strike>$49</strike> $29
Only $49 $29
Example: http://jsfiddle.net/eyks7zu9/3/
Below is your code, with a <span> tag added that has an ng-bind-html value. I could be totally wrong, as I'm not the best with angular myself, but I don't believe that what you are trying to do will work as you intend as Angular tries to keep the Sandbox model pretty rigid with regards to HTML injection.
var app = angular.module('app', []);
app.controller('ctrl', function($scope, $sce) {
$scope.price = $sce.trustAsHtml('Only <strike>$' + 49 + '</strike> $' + 29);;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span ng-bind-html="price"></span>
<br>Only <strike>$49</strike> $29
</div>

ng-keypress not triggering function

I'm new to AngularJS. I'm implementing ng-keypress events in AngularJS.
I referred to many blogs and tried to do as it is shown, but my code is not working!
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<input ng-keypress="change($event)" type="text" >
{{ text }}
</div>
</div>
script is:
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {
$scope.change=function($event){
$scope.text= 'a';
};
}]);
I'm trying to change the value of {{text}} on keypress.. but it's not working!
can anyone help me out!
Thanks :)
i tried the same things and its working
<body ng-controller="MainCtrl">
<input ng-keypress="change($event)" type="text" >
<pre>{{name}}</pre>
</body>
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.change=function($event){
$scope.name= 'hello';
};
});
checkout this plunker... PLUNKER LINK
EDIT
checkout your code plunker.. thats also working
EDIT
finally the answer is: 1.0.7 does not support ng-keypress, hence it was not working..
sometimes ng-keypress do not work on some browsers !!
i had the issue with the arrow keys in chrome
try ng-keydown instead (it worked for me )
As everyone else says it's working as it is supposed to do. Perhaps you want something like this?
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {
$scope.text = '';
$scope.change=function($event){
$scope.text += String.fromCharCode($event.keyCode);
};
}]);

Resources