0

Say I have the following directive called foo:

<div>
<label>Enter foo: </label>
<input ng-model="myModel"/>
</div>

And I use it like so:

<foo></foo>
<button>Add foo: </button>

What I am trying to do is dynamically add the foo directive on each button click and be able to have access to the new model variable that was created in the corresponding controller for this page.

Can this be done using angularJS?

1 Answer 1

1

First of all, if you plan to re-use <foo>, then you should create an isolated scope:

.directive("foo", function(){
   return {
      restrict: "E",
      scope: {
         data: "="
      },
      template: "<div><label>Enter foo: </label><input ng-model='data'/></div>"
   }
});

There is no difference between creating a custom directive or other tags. Without knowing too much about what you're doing, I could suggest the following:

app.controller("MainCtrl", function($scope)){
  $scope.fooModels = [];
  $scope.addFoo = function(){
      $scope.fooModels.push(new FooModel());
  };
}

FooModel() here is just a placehold for whatever the data model you need to represent foo data. You could also just do: $scope.fooModels.push({});.

Then in the view, simply ng-repeat your fooModels:

<div ng-repeat="fooModel in fooModels">
  <foo data="fooModel.data"></foo>
</div>
<button ng-click="addFoo()">Add Foo</button>

Here's a plunker to play with.

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

Comments

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.