Sukumar MS
Sukumar MS

Reputation: 748

is there any way to bind ng-model to multiple input fields uniquely inside a directive?

In my Project i Got a Issue like.I need to bind the user hobbies in the text field.if the user comes with a single hobby he can directly enter the hobby that he has. but when he had multiple then he had to click add multiple hobbies button.that working fine when i am displaying input fields dynamically using directives.but the issue is the value that coming from ng-model for that input field is binding to all input fields.

Here is my code.

Thanks in advance!

these are the images

this is how i am getting enter image description here

this is what i need enter image description here

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 is service to store user in localStorage.

In directive

'use strict';
angular.module('myApp')
  .directive('myHobby', function() {

    return {
      scope : false,
      templateUrl: 'views/my-hobby.html'
    };
  });

this is template: my-hobby.html

<div class="input-group">
<input type="text" ng-model="user.morehobies" class="form-control" placeceholder="type your hobbies here">

        <div class="close-icon">
        <span class="glyphicon glyphicon-remove" style="padding-left: 6px;"> </span>
        </div>
    </div>

Upvotes: 0

Views: 2556

Answers (1)

Nitish
Nitish

Reputation: 661

For this i would suggest some other way if its ok with you.

If your hobbies is coming in array, like

user.morehobies = ['Reading', 'Writing']

or create array for storing hobbies.

then inside directive you can pass that object in directive.

I will 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 your 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" then we can add empty string in hobbies object in directive.

and whenever user clicks on remove you can remove that item from array.

Upvotes: 1

Related Questions