0

I am trying to build an object like:
{"age":"21","name":"foo", "address":["address1", "address2"]}

For address I am using a custom directive, I don't know how to attach this to scope (person.address). If I give ng-model="person.address" in directive, it is taking same address for both the input texts. I have to isolate scope, but don't know where to put it.

Fiddle: http://codepen.io/goutham2027/pen/EagPZG

HTML

   <div ng-controller="testCtrl">
     <form>
       Name: <input type="text", ng-model="person.name"> <br/>
       Age:  <input type="text", ng-model="person.age"> <br/>
       Address-1 <address> </address>
       Alternate-Address <address>  </address>
     </form>
     {{person}}
      </div>

JS

app.directive('address', function() {
  return {
    restrict: 'E',
    template: '<input type="text">'
  }
})

Edit: I found out how to do it. Fiddle: http://codepen.io/goutham2027/pen/LEjaXP

1

4 Answers 4

1

Just add an isolated scope to your directive:

app.directive('address', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '='
    },
    template: '<input ng-model="ngModel" type="text">'
  }
})

http://codepen.io/anon/pen/raMxJo

Sign up to request clarification or add additional context in comments.

Comments

0

Try adding a person attribute to your controller.

app.controller('testCtrl', function($scope) {
  $scope.person = {age:"21",name:"foo", address:["address1", "address2"]};
});

As for using your custom directive to handle the two different address fields, go with the answer from @Rasalom.

Comments

0

You should give the directive a private scope, like so:

scope: {
  model: '='
}

Then you'll be able to pass it to your directive:

<address model="address"></address>

In your directive the address is now available in the HTML template through the private scope.

Comments

0

You can use isolated scope for that:

app.directive('address', function() {
  return {
    restrict: 'E',
    scope : {person:'='},
    template: '<input type="text" ng-model="person">'
  }
});

<div ng-controller="ctrl">
   <form>
     Name: <input type="text", ng-model="person.name">
     Age: <input type="text", ng-model="person.age"> <br/>
     Address-1: <address person="person.address1"> </address>
     Alternate-Address: <address person="person.address2"></address>
   </form>
</div>

CodePen example.

1 Comment

i want address in array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.