Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS adding text inside a <div>

Tags:

html

angularjs

In jQuery I can do something like the following to add desired text inside a div or any element.

$( "#div1" ).html( "<span class='red'>Hello <b>Again</b></span>" );

How can I do similar operation using AngularJS.

I need to add a plain text inside a div when the user clicks on a link.

Here's what I have tried:

View:

<a ng-click="showProductText($index)">Click Me</a>

ng-controller:

$scope.showProductText = function () {
   var myEl = angular.element(document.querySelector('#customerProductCatalogText'));
   --need help hence forth--
    };
like image 442
RandomUser Avatar asked Aug 07 '14 05:08

RandomUser


People also ask

How to add text inside div?

Use the insertAdjacentText() method to append text to a div element, e.g. container. insertAdjacentText('beforeend', 'your text here') . The method inserts a new text node at the provided position, relative to the element it was called on.

How to add content in div?

Add text to DIV using appendChild() Method in JavaScript (Method 2) You can also use the appendChild() method in JavaScript to add text or contents to a <div>.


2 Answers

In view

<div style="border:1px solid #ccc;padding:10px;" ng-bind-html="divText"></div>

and in Controller

$scope.divText = '<H2>some text</H2>';
like image 132
Shridhar Sagari Avatar answered Sep 20 '22 22:09

Shridhar Sagari


You can do that in different way "more angular then jQuery" using directive "ng-if" please see here http://jsbin.com/tuvom/1/edit

HTML

<body ng-app="app">
  <div ng-controller="firstCtrl">
    <div ng-repeat="item in products">
      <h4>{{item.name}}</h4>
      <button ng-if="!item.showdescription" ng-click="item.showdescription= !item.showdescription">Show description</button>
      <button ng-if="item.showdescription" ng-click="item.showdescription= !item.showdescription">Hide description</button>
      <p ng-if="item.showdescription">{{item.description}}</p>
    </div>
      </div>
</body>

JS

var app = angular.module('app', []);

app.controller('firstCtrl', function($scope){

  $scope.products = [

    {name:"item one", description:"so the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},
    {name:"item two", description:"so the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},

  ];
});
like image 26
sylwester Avatar answered Sep 19 '22 22:09

sylwester