angularjs - Injecting a HTML template to DOM on click the clean way (Create an instance of a class)? -
in angularjs project have (it's dropdown menu customer names. click on 1 of names scrum card should appear customer's names inserted in card.):
<ul class="dropdown-menu red" > <li ng-repeat="customer in customers" ng-click="addcard()"> // here goes html code </li> </ul>
i want accomplish card inserted on every click. problem is, card has multiple lines of html code. better insert whole new template. can't insert template ng-click, right? besides that, put html in variable , push list quite dirty, isn't it?
so, thought creating card class in coffeescript , create instance on every click. practive create class on click html template/partial? how tell angular create new instance of class card?
(before created directive had templateurl attribute partial. same problem: want inject directive on ng-click , not manually including directive in code ... btw, angular , coffeescript beginner ...)
thank in advance!
you should, in opinion, 2 things. apologies js , not coffeescript, intention same:
- create controller function call on ng-click. maybe have (since don't show addcard() defined). function should add instance of customer card class array bound $scope.
- if displaying 1 of these cards sufficiently complex, make new custom directive displaying card , use inside ng-repeat.
example:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <script type="text/javascript"> function card() { this.name = 'bob'; this.phone = '1234567'; } angular.module('myapp', []); angular.module('myapp').controller('customercardcontroller', function ($scope) { $scope.cards = []; $scope.addcard = function() { $scope.cards.push(new card()); }; }); angular.module('myapp').directive('mycard', function(){ return { restrict: 'a', template: '<div>{{acard.name}} {{acard.phone}}</div>', replace: true, transclude: false, scope: { acard: '=mycard' } }; }); </script> </head> <body ng-app="myapp"> <div ng-controller="customercardcontroller"> <div ng-click="addcard()">add new card</div> <div ng-repeat="card in cards" my-card="card"></div> </div> </body> </html>
Comments
Post a Comment