I receive next string (it should be 2 rows):
commentBody:"row 1↵row 2"
I need to render it in two rows.
But unfortunately in my html code it renders in all in one row.
<div ng-if="!comment.openEdit" ng-bind-html="comment.commentBody" class="workItemCommentBody"></div>
Since you didn't provide all the code I am assuming you're using either ngSanitize or $sce.
Read AngularJS Insert HTML into view.
If you want to insert multi line string, first you should replace the line breaks in the string with the <br/>.
Read
Replace line breaks with <br/>
I tweaked the regex to match ↵ character while replacing line breaks.
So below is what it looks
angular
.module('myApp', []);
angular
.module('myApp')
.controller('MyController', MyController);
MyController.$inject = ['$scope', '$sce', '$interpolate'];
function MyController($scope, $sce, $interpolate) {
var commentBody = "row 1↵row 2";
commentBody=commentBody.replace(/(?:\r\n|\r|\n|\↵)/g, '<br />');
$scope.comment = {
openEdit: false,
commentBody: $sce.trustAsHtml(commentBody)
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController as MC">
<div ng-if="!comment.openEdit" ng-bind-html="comment.commentBody" class="workItemCommentBody"></div>
</div>
Related
I was trying to count the length of a string($scope.count = $scope.str.lenght). But, when there is a space at the end of the string its not being counted until there is a character after the space.
Example:
"Hello " = 5,
"Hello u" = 7
Any idea why is it designed in this way?
How can I count the space at the end of the string?
By default Angular will trim the trailing spaces on ngModel. To override this behaviour add:
ng-trim="false"
more info
(function() {
'use strict';
angular.module('myApp', []);
angular.module('myApp').controller('MyController', MyController);
MyController.$inject = [];
function MyController() {
var main = this;
main.someText = 'abcde';
}
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyController as main">
<input type="text" ng-model="main.someText" ng-trim="false">
{{main.someText.length}}
</div>
</body>
May be your having the problem with angular ngModel not for the Javascript. Because it is working correct in javascript
console.log("hello ".length)
console.log("hello u".length)
In Angularjs I would suggest #giovani answer
I know there are other questions about this, but I already tryed and nothing seems to work.
I basically have an angular variable retrieved from an $http.get .
The content is html encoded, like:
Paperwhite – Human Nature
So I have to display it as
<div ng-bind-html="songrel.title.rendered"></div>
To render the html:
Paperwhite – Human Nature
I want to split this value for the - and display only
Human Nature
I tryed something like
<div ng-bind-html="songrel.title.rendered.split('–')[1]"></div>
or
<div ng-bind-html="songrel.title.rendered.split('-')[1]"></div>
Or moving the code in my app.config
$scope.showFirstBr = function(content){
return content.split('–')[1]
};
and then
<div ng-bind-html="showFirstBr(songrel.title.rendered)"></div>
but nothing seems to work. What am I missing?
Try this
var app = angular.module("MyApp", []).controller("MyCtrl", function($scope, $sce) {
var str = 'Paperwhite – Human Nature';
$scope.test = $sce.trustAsHtml(str.split('–')[1]);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="MyApp" ng-controller="MyCtrl">
<div ng-bind-html="test"></div>
</body>
I've fixed adding this in the controller:
$scope.showFirstBr = function(content){
var c = content.replace('–','-');
return c.split('-')[1]
};
I am learning Angular using W3Schools.
I just modified an example about "Services"... The following is the code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{hex}}</h1>
</div>
<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
When I update the textbox, the "HEX" part is not updating. Why?
Your hexafy.myFunc is called only once when the controller is initialized, hence only the initial value is converted to hex. If you want a function to be called on the value change of a scope variable in runtime, you need filters. AngularJS has a lot of inbuilt filters that are ready to use.
You can also define a custom filter, just like you define services or controllers.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{num | hexafy}}</h1>
</div>
<p>A custom filter that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.filter('hexafy', function() {
return function (x) {
return Number(x).toString(16); // Also convert the string to number before calling toString.
}
});
app.controller('myCtrl', function($scope) {
$scope.num = 200;
//$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
Further reading: AngularJS Filters
NOTE: A filter is a good idea if you're gonna be using the hexafy functionality at multiple places in/across views. Otherwise, it is just an overkill and the $scope.$watch method will work fine for you, as described in other answers
$scope.hex is not updating because there're no way for it update itself.
The hexafy.myFunc is called only once when the controller is loaded for the first time.
If you want want the $scope.hex property to change with num, you might need a watch on the num property.
$scope.$watch('num', function(newVal, oldVal) {
$scope.hex = hexafy.myFunc($scope.num); /// or newVal
}
The function passed in $scope.$watch will be called everytime the value of $scope.num changes.
for more info see https://docs.angularjs.org/api/ng/type/$rootScope.Scope (the watch section)
Hope it helps.
No need of a service here, you can simple use $watch on the num. See below code snippet, it will update your ui, I have updated your controller code, please check.
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = "some default val";
$scope.$watch('num', function(newValue, oldValue) {
$scope.hex = newValue.toString();
});
});
Your Text box is only bind to 'num'. '$scope.hex is not binded to your text box'. So that it is not update when you typing text. You could use '$watch' on 'num'. Read here
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.$watch('num', function() {
$scope.hex = hexafy.myFunc(parseInt($scope.num));
});
});
How to send the json data from FirstCtrl to secondCtrl using angularjs.
Can anyone please help me out regarding this ...
First.js:
angular.module('myApp')
.controller('FirstCtrl', function ($scope) {
//firstCtrl json data
$.getJSON("sample.json", function (json) {
console.log(json);
});
});
Second.js:
angular.module('myApp')
.controller('secondCtrl', function ($scope) {
//get the firstCtrl json data here
});
I would also suggest a service that gets and returns data from and to the controllers.
we create the two controllers and then we create a service with two functions:
1. one to get the json data
2. one to return the json data
Like so:
'use strict';
angular.module('myApp', [])
.controller('FirstCtrl', function( $scope, myService ){
//we create or get the json object
$scope.myjsonObj = {
'animal':'cat',
'feed':'frieskies',
'color':'white',
'sex':'male'
};
//pass the json object to the service
myService.setJson($scope.myjsonObj);
})
.controller('SecondCtrl', function( $scope, myService ){
//call service getJson() function to get the data
$scope.myreturnedData = myService.getJson();
})
.factory('myService', function(){
var myjsonObj = null;//the object to hold our data
return {
getJson:function(){
return myjsonObj;
},
setJson:function(value){
myjsonObj = value;
}
}
});
and the HTML partial would be:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
{{myjsonObj}}
</div>
<hr>
<div ng-controller="SecondCtrl">
{{myreturnedData.animal}}
{{myreturnedData.feed}}
{{myreturnedData.color}}
{{myreturnedData.sex}}
</div>
Hope helps, good luck.
If the second controller is nested you can use $parent to access the scope of the first controller. You would need to assign the value of json to $scope such as
$scope.json = my_json
Then in the second controller you can say
$scope.json = $scope.$parent.json;
var app = angular.module('myApp', []);
app.controller('Ctrl1', function ($scope, $rootScope) {
$scope.msg = 'World';
$rootScope.name = 'AngularJS';
});
app.controller('Ctrl2', function ($scope, $rootScope) {
$scope.msg = 'Dot Net Tricks';
$scope.myName = $rootScope.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html>
<body ng-app="myApp">
<div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px">
Hello {{msg}}!
<br />
Hello {{name}}!
(rootScope)
</div>
<br />
<div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
Hello {{msg}}!
<br />
Hey {{myName}}!
<br />
Hi {{name}}! (rootScope)
</div>
</body>
</html>
Yo can simply make a new service with two functions one to save the date and one to give them, this service then can be accessed from any where.
In addition, you can assign the data to a $rootScope.someVar for example, and in this way too you can retrieve the data from any where
Just use $rootScope to achieve this.
In your first controller assign $rootScope.json = $scope.json; and It will available on the entire application. So, you can access $rootScope.json wherever you want on that particular app
Is it possible to render template with AngularJs not on Page, but probably in memory? I need to prepare html to be send as email.
I guess i could render something in hidden div, then in some way assign it content to variable , but for me it looks ugly :(
You can take a look at $compile function: http://docs.angularjs.org/api/ng.$compile
Example:
function MyCtrl($scope, $compile){
// You would probably fetch this email template by some service
var template = '</div>Hi {{name}}!</div></div>Here\'s your newsletter ...</div>'; // Email template
$scope.name = 'Alber';
// this produces string '</div>Hi Alber!</div></div>Here\'s your newsletter ...</div>'
var compiledTemplate = $compile(template)($scope);
};
Sure, you can use the $compile service to render a template. The rendered template will be a DOM node that isn't attached to the DOM tree. And you don't have to attach it to get its content. You could do something like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile){
var compiled;
$scope.compileTemplate = function() {
var template = '<ul><li ng-repeat="i in [1, 2, 3]">{{i}}</li></ul>';
var linker = $compile(template);
compiled = linker($scope);
}
$scope.sendEmail = function() {
alert("Send: " + compiled[0].outerHTML);
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="compileTemplate()">Compile template</button>
<button ng-click="sendEmail()">Send email</button>
</body>
</html>
The reason that I've divided them into two different functions here is because when you compile and link it to the scope, the template isn't filled with data until after the next digest. That is, if you access compiled[0].outerHTML at the end of the compileTemplate() function, it won't be filled (unless you use a timeout...).