Display Div From Response In Angularjs
Problem Question -- I have a Controller in AngularJs which perform the $http.get and in response it gets the Data(Which also has HTML DivID and .Class). How would I take this DivID
Solution 1:
I assume what you are trying to do is to render the returned html instead of printing the html content in the UI.
In that case you can use the ngBindHTML directive like
var app = angular.module('my-app', ['ngSanitize']);
app.controller('MyController', ['$scope',
function($scope) {
$scope.myhtml = '<div class="myclass">some content</div>'
}
])
.myclass {
color: red;
}
<scriptsrc="https://code.angularjs.org/1.2.9/angular.js"></script><scriptsrc="https://code.angularjs.org/1.2.9/angular-sanitize.js"></script><divng-app="my-app"ng-controller="MyController"><div>{{myhtml}}</div><divng-bind-html="myhtml"></div></div>
Solution 2:
As suggested by Arun, you need a directive. It seems that you want to pass the HTML retrieved elsewhere to the view (as opposed to the directive fetching the HTML on its own). I guess you could create a directive that extracts stuff from HTML.
app.directive("find", function($compile){
var html = "";
var selector = "";
// use jQuery to construct an object from html and .find using the selectorfunctionrender(scope, elem){
if (html === "") return;
var jqHtml = angular.element("<div>").html(html).find(selector);
elem.empty();
elem.html(jqHtml.html());
// $compile, such that any directives/expressions in the imported HTML //are compiled and linked to the right scope$compile(elem.contents())(scope);
}
return {
restrict: "E",
scope: true,
link: function(scope, elem, attrs){
// $observe the attributes for changes
attrs.$observe('selector', function(newValue){
selector = newValue;
render(scope, elem);
});
attrs.$observe('html', function(newValue){
html = newValue;
render(scope, elem);
});
}
};
});
The usage is:
<find html="{{html}}" selector="#t1"></find>
Post a Comment for "Display Div From Response In Angularjs"