javascript - is there any way to bind ng-model to multiple input fields uniquely inside a directive? -
in project got issue like.i need bind user hobbies in text field.if user comes single hobby can directly enter hobby has. when had multiple had click add multiple hobbies button.that working fine when displaying input fields dynamically using directives.but issue value coming ng-model input field binding input fields.
here code.
thanks in advance!
these images
in html
<div> <div id="showhobbyfield"></div> <input type="number" class="form-control" placeholder="add hobbies" ng-click="addhoby()"> </div>
in controller
$scope.addhoby= function(){ var compiledehtml = $compile("<div my-hobby></div>")($scope); $("#showhobbyfield").append(compiledehtml); }; $scope.adduser = function(){ $scope.users= []; var obj = { userhobby : $scope.user.morehobies }; $scope.users.push(obj); menustorage.put($scope.users);
//menustorage service store user in localstorage.
in directive
'use strict'; angular.module('myapp') .directive('myhobby', function() { return { scope : false, templateurl: 'views/my-hobby.html' }; });
this template: my-hobby.html
<div class="input-group"> <input type="text" ng-model="user.morehobies" class="form-control" placeceholder="type hobbies here"> <div class="close-icon"> <span class="glyphicon glyphicon-remove" style="padding-left: 6px;"> </span> </div> </div>
for suggest other way if ok you.
if hobbies coming in array,
user.morehobies = ['reading', 'writing']
or create array storing hobbies.
then inside directive can pass object in directive.
i use ng-repeat inside directive.
<div class="input-group" ng-repeat="h in hobies"> <input type="text" ng-model="h" class="form-control" placeceholder="type hobbies here"> <div class="close-icon"> <span class="glyphicon glyphicon-remove" style="padding-left: 6px;"> </span> </div> </div>
so whenever user clicks on "add hobbies" can add empty string in hobbies object in directive.
and whenever user clicks on remove can remove item array.
Comments
Post a Comment