Dynamically add element to DOM in angular - javascript

This is how my page looks like on initial load
<body>
<div class="col-md-12" id="dataPanes">
<div class="row dataPane"> Chunk of html elements </div>
</div>
<div class"col-md-12 text-right">
<input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</body>
I am in need to add rows to div#dataPanes on button click
If I was using jQuery,addElementChunk() function would have looked as below
var addElementChunk = function()
{
var html = "<div class='row dataPane'> Chunk of html elements </div>";
$("#dataPanes").append(html);
}
but how do I implement the same in angular??

You need to use $compile
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
and $sce
Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
addElementChunk = function(){
var html = '<div class="row dataPane"> Chunk of html elements </div>';
var trustedHtml = $sce.trustAsHtml(html);
var compiledHtml = $compile(trustedHtml)($scope);
angular.element(document.getElementById('dataPanes')).append(compiledHtml);
}

you can append new div using angular ng-repeat directive
lets say you have an array that contain one element and every time you click the button you add another element to the array, while you are repeating it in your "dataPane" div
so you code could be:
HTML
<div ng-app="myApp" ng-controller="myCtr">
<div class="col-md-12" id="dataPanes">
<div class="row dataPane" ng-repeat="element in added_elements"> Chunk of html elements ( {{element}} ) </div>
</div>
<div class="col-md-12 text-right">
<input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addMoreElements()" />
</div>
</div>
JS
angular
.module('myApp', [])
.controller('myCtr', ['$scope', function($scope) {
$scope.added_elements = ["elem 1"];
$scope.addMoreElements = function(){
$scope.added_elements.push("elem "+ ($scope.added_elements.length+1));
}
}])
so you can add whatever data you want about your repeated row and bind it in html in simple way without having to repeat the whole html code
Working Demo

You can also append a new html element in this way. I think its very easy to write and also understand. hope it will help you.
angular.element used to access the html element.
Here is the html code:
angular.module('myApp',[]).controller('myCtrl', function($scope){
$scope.addElementChunk = function()
{
var htmlStr = '<div class="row dataPane"> Chunk of html elements </div>';
debugger;
angular.element(document.getElementById('dataPanes')).append(htmlStr);
}
});
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-12" id="dataPanes">
<div class="row dataPane"> Chunk of html elements </div>
</div>
<div class="col-md-12 text-right">
<input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</div>
</div>
Here is the fiddle link

Related

Modal window comment editing module (editable text)

I want to make, that during the ediditing comment action, I have modal window with comment text written inside textarea, and it is editable without deleting all text with clicking. I tried just to put value inside textarea or placing it in placeholder. But both options are wrong and doesnt work.
Can someone take a look on this code and give me an advice, how should I take for it.
editComment.html
<div class="modal-header">
<h3 class="modal-title" id="modal-title">Edytuj komentarz</h3>
</div>
<div class="modal-body" id="modal-body">
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12 form-group">
<label>Treść</label>
<textarea class="form-control input-sm"
name="description"
ng-maxlength="512"
ng-model="$ctrl.selected"
rows="6">{{comment.value()}}</textarea>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-raised btn-primary"
type="button"
ng-disabled="!$ctrl.selected"
ng-click="$ctrl.ok()">Zapisz
</button>
<button class="btn btn-raised btn-warning"
type="button"
ng-click="$ctrl.cancel()">Anuluj
</button>
</div>
editComment.js
(function() {
'use strict';
angular.module('settlerApplication').controller('EditCommentCtrl', function($uibModalInstance) {
var $ctrl = this;
$ctrl.ok = function() {
$uibModalInstance.close($ctrl.selected);
};
$ctrl.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
});
})();
I'm not sure to understand what you are trying to achieve. But anyway : if you want to init your textarea's ng-model with $ctrl.foo (comment.value() in your case, from what I understood), you should either :
In the controller, init your $ctrl.selected variable with this value :
$ctrl.selected = $ctrl.foo;
Or, in your template, use ng-init :
<textarea class="form-control input-sm"
ng-init="$ctrl.selected = $ctrl.foo"
name="description"
ng-maxlength="512"
ng-model="$ctrl.selected"
rows="6"></textarea>
Ok, so I am going to explain that a little.
I have modal window like that:
I want to edit existing comments in this window. And so I want my comment appears instead of text: "Komentarz" (under: "Treść" after clicking in there). And I want that comment text to be editable, so I dont have to write it down again (put the whole text to that area). Is it make it a little better explained about my goal?

Show a div with AngularJS

I am searching how to show a div with AngularJS. I read some topic on StackOverflow but when I try to apply them, it doesn't works for my case...
This is my HTML code :
<div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
<div id="DivWhereIsMyButton" class="clearfix" ng-controller="controllerBubble">
Another div where is my button
<div id="containerButton" ng-controller="controllerDependance">
<button class="btn btn-danger btn-lg pull-right"
ng-click="showAlert()">View dependances
</button>
</div>
</div>
This is the controller :
d3DemoApp.controller('controllerBubble', function () {
});
d3DemoApp.controller('controllerDependance', function ($scope) {
$scope.myvalue = false;
$scope.showAlert = function(){
$scope.myvalue = true;
};
});
I initially thought, it is controllerOther take the hand and cancel the controllerDiv but even if I separate the both, it doesn't works. The problem is I am obligated to put the both in two differents controllers.
I have two controllers, controllerDependance and controllerBubble. My div to show is in the controllerDependance. My button is in a div controllerBubble and I can't move it. So I would like to wrap it in a div controllerDependance.
I make a Plunker to show you the problem : https://plnkr.co/edit/z1ORNRzHbr7EVQfqHn6z?p=preview
Any idea ?
Thanks.
Put the div you want to show and hide inside the controller. It needs to be within the scope of the controller, otherwise your controller function cant see it. Also, consider what you are trying to accomplish with the nested controllers, I often find them unnecessary.
<div id="divButton" class="clearfix" ng-controller="controllerOther">
<div id="buttonToShowDiv" ng-controller="controllerDiv">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">Show my div</button>
<div id="myDiv"ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
</div>
</div>
I notice in your original example you are declaring ng-controller="controllerDependance" twice in the DOM. I have never tried this before, but I can imagine this will cause problems. From the angular documentation on controllers
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope
I imagine that this is what is causing you problems. You have to have the div you want to show/hide within the scope of your controller.
I got your plunkr working, you can see my version here: https://plnkr.co/edit/NXbsVFMNHR8twtL8hoE2?p=preview
The problem was stemming from you declaring the same controller twice, and more importantly, the div to show/hide was using ng-show with a value from your mainController. But your div was outside that controller. So ng-show cant see the value. The div has to be withing the scope of the controller
You are using two different controllers which have different $scopes therefore their values are not connected! To show or hide a div is really simple in angular:
<div id="divButton" class="clearfix" ng-controller="myController">
<div id="buttonToShowDiv">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">Show my div</button>
</div>
<div id="myDiv" ng-show="myvalue" class="ng-cloak">
Blablabla
</div>
</div>
And the script side just almost the same:
d3DemoApp.controller('myController', function AppCtrl ($scope) {
$scope.myvalue = false;
$scope.showAlert = function(){
$scope.myvalue = true;
};
});
Since you question was how to show elements using angular, I took the liberty of using just one controller.
Create a factory that will return an object and let your controllers work with a reference to the same object:
var d3DemoApp = angular.module('app', [])
d3DemoApp.factory('MyValue', function () {
return { value: false };
});
d3DemoApp.controller('controllerBubble', function ($scope, MyValue) {
$scope.myvalue = MyValue;
});
d3DemoApp.controller('controllerDependance', function ($scope, MyValue) {
$scope.myvalue = MyValue;
$scope.showAlert = function(){
$scope.myvalue.value = true;
};
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-app="app">
<div ng-controller="controllerBubble" class="clearfix">
<div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue.value" class="ng-cloak">
Blablabla
</div>
</div>
<div id="DivWhereIsMyButton" class="clearfix" ng-controller="controllerBubble">
Another div where is my button
<div id="containerButton" ng-controller="controllerDependance">
<button class="btn btn-danger btn-lg pull-right" ng-click="showAlert()">View dependances</button>
</div>
</div>
</div>
</body>
</html>

How to pass HTML element into angularjs code?

I want to pass the html element into angularjs code. I have some html elements like data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" I want to access these Html elements in angularjs code.
My html templates, what make to change in the following code so that its elements accessible to angularjs code.
<div class="info row detail">
<div class="col-sm-9 chart_container">
<div class="chart"
data-chart-type="line_chart"
data-url="{% url 'horizon:admin:metering:samples'%}"
data-form-selector='#linechart_general_form'
data-legend-selector="#legend"
data-smoother-selector="#smoother"
data-slider-selector="#slider">
</div>
<div id="slider"></div>
<div class="col-sm-3 legend_container">
<div id="smoother" title="Smoothing"></div>
<div id="legend"></div>
</div>
</div>
</div>
--Update-- I just reread your question. To access those ATTRIBUTES (not elements, they are values of an element) you can select the object with an identifier, then manipulate it's attributes, like so (jQuery example):
$('.chart').attr('data-form-selector', 'myNewValue');
You may need to re-initialize sopmething because of the databinding but that's where I'd start.
==================================
You need to create an angular app and controller first, then use the angularjs and ng-model directive to bind the element to a method in your controller, i.e.:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
In this case, you'd be manipulating the $scope.firstName and $scope.lastName variables in js.
Courtesy W3Schools
http://www.w3schools.com/angular/angular_intro.asp
You can do a Directive for doing that.
https://docs.angularjs.org/guide/directive

AngularJS Dynamic Template with indexed scope variable arrays

I'm using AngularJS and trying to create a form where I can dynamically add new inputs, similar to this fiddle: http://jsfiddle.net/V4BqE/ (Main HTML below, working code in fiddle).
<div ng-app="myApp" ng-controller="MyCtrl">
<div add-input>
<button>add input</button>
</div>
</div>
I would like to be able to use a HTML template for my form since the input I'm adding is ~300 lines long. My issue is I cannot figure out how to index the scope variable containing the data when used in a template. I've tried to make my own modified version of the above code on plnkr http://plnkr.co/edit/4zeaFoDeX0sGTuBMCQP2?p=info . However, when I click the button no form elements appear.
Online (plnkr) I get a 404 not found for my template.html, but I think that is just a plnkr limitation. On my machine with a Python HttpServer I get an Error: [$parse:syntax] for the $templateRequest and a TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. when using the $http.get method.
Any advice for getting the indexed scope variable array to work with an external html file?
Thanks, JR
Edit: Update plnkr link
You can do it without directive & external template
what you are trying to do does not require a directive (it actually much simple with the basic angularjs tools)
http://plnkr.co/edit/LVzGN8D2WSL2nR1W7vJB?p=preview
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<div ng-repeat="item in telephoneNumbers">
<hr>
<input type="text" ng-model="item.phone">
</div>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
If you insist using a directive,
http://plnkr.co/edit/BGLqqTez2k9lUO0HZ5g1?p=preview
phone-number.template.html
<div>
<hr>
<input type="text" ng-model="ngModel" >
</div>
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<phone-number ng-repeat="item in telephoneNumbers" ng-model="item.phone"></phone-number>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
app.directive('phoneNumber', function(){
return {
replace:true,
scope: {
ngModel: '=',
},
templateUrl: "phone-number.template.html"
}
});

Reset data on click for a different controller

I have two divs - the first contains the second. The contained div has its own controller. When I click an icon button in the container, I change a variable which then affects the visibility of the contained div.
It looks like this:
<div ng-controller="BarController">
<div class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="col-lg-2 page-title">My Page</div>
<div class="col-lg-10">
<span class="actions">
<i class="fa fa-lg fa-download fa-inverse" tooltip="Download"
ng-click="showSecondaryBar=!showSecondaryBar"></i>
</span>
</div>
</div>
</div>
<div class="download navbar download-in download-out"
ng-class="{'myhidden': !showSecondaryBar}"
ng-cloak>
<div class="col-lg-offset-4 col-lg-4 form-inline form-group" ng-controller="TagsController">
<div class="download-label col-lg-6">
<label>Download by tags:</label>
</div>
<div class="download-tags col-lg-6">
<tags-input class="bootstrap" spellcheck="false" min-length="1" ng-model="tags" add-from-autocomplete-only="true">
<auto-complete source="loadTags($query)" min-length="1" load-on-down-arrow="true"
load-on-focus="true" max-results-to-show="5"
highlight-matched-text="false"></auto-complete>
</tags-input>
</div>
</div>
</div>
</div>
The <tags-input> is taken from ng-tags-input and I would like to reset the tags that were already typed to it whenever the icon button is clicked (which changes the visilibyt of the div that contains the ng-tags-input).
Problem is, because I have the TagsController which contains the data (tags) and this data is not visible in the BarController, I'm not sure how I can reset the tags array to become empty.
I thought of using a service but it fills like too much of a coupling. I would prefer to have a function in TagsController which is called upon click. But I can't figure out how to do it from another controller
You are right you have to use a service.
Why don't you use a broadcast as your TagsController is included in BarController?
You can include a scope.broadcast("Event") in BarController
Then a "on" listener on TagsController who will reset the tags array when "Event" Occur.
I would personnaly to this.
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
You can use $broadcast on $rootScope to send an event to TagsController. So TagsController can receive this event by registering an event listener for it. See following example.
Refer to $rootScope API docs
angular.module('app',[])
.controller('ParentController', function($rootScope) {
var parentCtrl = this;
parentCtrl.someFlag = true;
parentCtrl.changeFlag = function() {
parentCtrl.someFlag = !parentCtrl.somFlag;
$rootScope.$broadcast('resettags', {'defaultTags': 'whatever_tag'});
}
})
.controller('ChildController', function($rootScope){
var childCtrl = this;
childCtrl.tags = "Some tags entered by user";
$rootScope.$on('resettags', function(event, args) {
childCtrl.tags = args.defaultTags;
});
});
.myHidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div id="main" ng-controller="ParentController as parentCtrl">
<button type="button" ng-click="parentCtrl.changeFlag()">Toggle</button>
<div ng-class="{'myHidden' : !parentCtrl.someFlag}">
<div ng-controller="ChildController as childCtrl">
<h1>{{childCtrl.tags}}</h1>
</div>
</div>
</div>
</div>

Categories

Resources