Austin Hunter
Austin Hunter

Reputation: 394

Dynamically Creating HTML Buttons from Angular

I've done some research but I can't find any tutorials or examples. So I thought I would put this out there for someone to answer.

I am trying to create buttons in angular to show up in html. I don't have much code, but here's what I have:

angular.module('starter.controllers', ['ionic'])

.controller('HomeCtrl', function($ionicPopup, $scope) {
  }
<ion-content ng-controller="HomeCtrl">
			<div id="createdBtns" style="margin: 20px">
				<button class="button button-block">Groups</button>
			</div>
			<button id="staticBtn" class="button button-float" ng-click="addContact()">
				<i class="icon ion-plus"></i>
			</button>
		</ion-content>

That button won't be there inside the first div. It is just an example of what I want, but created dynamically in angular I need to create buttons within the HomeCtrl. Can anyone help me out with this?

What I am trying to do:

I will be asking a user for their name. Once I get it, I will create a button on the screen with their name on it. Like this:

.controller('HomeCtrl', function($ionicPopup, $scope) {
	$scope.addContact = function() {
		$ionicPopup.confirm({
			title: 'Import?',
			template: 'Would you like to import a contact from your current contacts?',
			cancelText: 'No',
		    okText: 'Yes'
		}).then(function(res) {
			if (res) {
				navigator.contacts.pickContact(function(contact) {
					 alert('The following contact has been selected:' + JSON.stringify(contact));
				})

So then I will create a button with their contact information on it.

Upvotes: 2

Views: 3299

Answers (2)

devqon
devqon

Reputation: 13997

This sounds like the basic angular functionality. You first have to define some $scope data:

.controller('HomeCtrl', function($ionicPopup, $scope) {
    // or whatever information your contacts have
    $scope.contacts = [];

    // the code that picks a contact
    //..
    navigator.contacts.pickContact(function(contact) {
        $scope.contacts.push(contact);
    })

    $scope.doSomethingWithContact = function(contact) {
        console.log(contact);
    }
}

Then in your html something like:

<button class="button button-block"
        ng-repeat="contact in contacts"
        ng-click="doSomethingWithContact(contact)">
    {{ contact.displayName }} (phone: {{ contact.phoneNumbers[0] }})
</button>

Upvotes: 2

Nikolai
Nikolai

Reputation: 318

In the controller's code you would need to create a collection of buttons and assign it to scope. Then in your HTML use ngRepeat directive to iterate through that collection and create required buttons. See below code for an example

https://run.plnkr.co/plunks/jASWuwDMX0ojIj3XLZMX/

Upvotes: 1

Related Questions