nobody
nobody

Reputation: 8263

ng-click to replace DOM element with angular directive

So I was wondering if it was possible to have an ng-click statement on a span that when clicked would replace the spans content with a directive (with it's template, bindings, etc)?

Example

 <div class="col-xs-12">
    <span ng-click="edit"> {{ user.name }} - {{ user.lastWin }} </span>
        <button ng-click="removeUser(user.name)" class="btn btn-danger pull-right margin-right-10">Remove User</button>
  </div>

the edit would then be this:

<form name="editUser">
  <input type="text" name="name" ng-model="name" placeholder="Name"/>
  <input type="text" ng-model="lastWin" placeholder="Last Win"/>
</form>
<button ng-click="editUser($index, { name: name, lastWin: lastWin })" class="btn">Save</button>

what would i have to do on my controller to get it to swap everything correctly?

Upvotes: 1

Views: 2458

Answers (2)

Chandermani
Chandermani

Reputation: 42669

Having ng-if logic in view is fine. If you want to get rid of ng-if declare two templates in html

<script type='text/ng-template' id='view'>
<!--Read only content here-->
<script>

<script type='text/ng-template' id='edit'>
<!--Form content here-->
<script>

And then use ng-include

<div ng-include='template'></div>

In you controller you set the activeTemplate based on current state in your ng-click

if(edit) {
   $scope.template='edit';
}
else {
   $scope.template='view';
}

Upvotes: 0

Fresheyeball
Fresheyeball

Reputation: 30015

I would use an ng-if and do the whole thing with no additional javascript

something like this:

<div class="col-xs-12" ng-if="!edit">
    <span ng-click="edit = true"> {{ user.name }} - {{ user.lastWin }} </span>
    <button ng-click="removeUser(user.name)" class="btn btn-danger pull-right margin-right-10">Remove User</button>
</div>
<div ng-if="edit">
    <form name="editUser">
      <input type="text" name="name" ng-model="name" placeholder="Name"/>
      <input type="text" ng-model="lastWin" placeholder="Last Win"/>
    </form>
    <button ng-click="editUser($index, { name: name, lastWin: lastWin })" class="btn">Save</button>
</div>

Upvotes: 2

Related Questions