hughesjmh February 2016

Reusing a directive template for multiple forms with isolated scope

I'm working on a project where the user needs to be able to create many instances of the same form. As of now the user can click a button to create one or more forms. The problem I'm having is that by isolating the scope, as I think I should be doing given that I'm reusing the same directive, my ng-models can't communicate with the parent controller.

My directive for <rule-form></rule-form>..

(function(){
'use strict';

var ruleForm = function(){
    return{
        restrict: 'E',
        replace: true,
        scope: {},
        templateUrl: 'edit/rule-create/ruleForm.html',
        link: function(scope, element, attrs){
            scope.length = document.forms.length;   
        }
    }
}

angular.module('ganeshaApp')
.directive('ruleForm', ruleForm)
})();

And my template...

<form class="edit__div--rule-form" name="form_{{length}}">
<input type="text" placeholder="Rule Title" ng-model="rcCtrl.ruleTitle">
<div class="edit__div--rc-toolbar">
    <select class="edit__btn--rc-select" ng-model="rcCtrl.select" apply-statement-type>
        <option value="obligation statement">obligation statement</option>
        <option value="prohibition statement">prohibition statement</option>
        <option value="permission statement">restricted permission statement</option>
    </select>
    <div class="edit__btn--rc-noun">
        Add noun/verb
    </div>
    <div class="edit__btn--rc-save" ng-click="rcCtrl.saveRule()">
        <span class="glyphicon glyphicon-floppy-saved"></span>Save
    </div>
    <div class="edit__btn--rc-cancel">
        <span class="glyphicon glyphicon-remove"></span>
        Cancel
    </div>
</div>
<div class="edit__select--statement-type"></div>

<div ng-show="rcCtrl.showTextEdit" class="edit__div--rule-form-        

Answers


georgeawg February 2016

Add a controller to your directive.

angular.module('ganeshaApp').directive('ruleForm', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        templateUrl: 'edit/rule-create/ruleForm.html',
        controller: "rulesFormController as rcCtrl",
        link: function(scope, element, attrs){
            scope.length = document.forms.length;   
        }
    }
});

The AngularJS $compile service will then create an instance of the controller for each instance of the directive and attach it to each isolate scope.

For more information, see the AngularJS Comprehensive Directive API Reference.

Post Status

Asked in February 2016
Viewed 2,914 times
Voted 4
Answered 1 times

Search




Leave an answer