1

我正在开发一个项目,用户需要能够创建相同表单的许多实例。到目前为止,用户可以单击一个按钮来创建一个或多个表单。我遇到的问题是通过隔离范围,因为我认为我应该这样做,因为我正在重用相同的指令,我ng-models无法与父控制器通信。

我的指令<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)
})();

还有我的模板...

<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-text" contenteditable="true" ng-model="rcCtrl.ruleText"></div>

我尝试使用$parent, (例如$parent.rcCtrl.ruleText),但后来我又回到了没有隔离范围的问题,并且每个表单都会更新其他表单。我真的有点困惑。有谁知道这个问题的解决方案,还是只是我的代码有问题?

4

1 回答 1

0

将控制器添加到您的指令中。

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;   
        }
    }
});

然后,AngularJS$compile服务将为指令的每个实例创建一个控制器实例,并将其附加到每个隔离范围。

有关更多信息,请参阅AngularJS 综合指令 API 参考

于 2016-02-08T23:59:38.473 回答