将控制器的功能添加到角度中的特定视图

Adding functionality of controllers to certain view In Angular

本文关键字:视图 控制器 功能 添加      更新时间:2023-09-26

我有一个名为129.html的视图,它的格式如下。这基本上是从json文件中读取的一堆问题。

<div class="" ng-repeat="group in groups">
        <h2 ng-bind="group.title"></h2>
        <div class="" ng-repeat="section in group.sections">
            <div class="" ng-repeat="field in section.fields">
                <!-- textfield -->
                <div class="form-group" ng-class="{ 'has-error': form.$submitted && form[field.id].$invalid }" ng-if="field.type === 'text'">
                    <!-- <label for="{{field.id}}">{{field.title.substr(field.title.indexOf('.') + 2)}}</label><br> -->
                    <label for="{{field.id}}">{{field.title}}</label>
                    <br>
                    <input type="text" class="form-control" id="{{field.id}}" name="{{field.id}}" ng-model="formData[field.id]" ng-required="field.validations.required" ng-minlength="field.validations.min_length">
                    <p class="form-group-note" ng-if="field.info" ng-bind="field.info"></p>
                    <div ng-show="form.$submitted" ng-cloack>
                        <span class="help-block" ng-show="form['{{field.id}}'].$error.required" ng-if="field.validations.required">Please enter a value, this field is required</span>
                        <span class="help-block" ng-show="form['{{field.id}}'].$error.minlength" ng-if="field.validations.min_length">Please enter a value of at least {{field.validations.min_length}} characters</span>
                    </div>
                </div>
     </div>
</div>

Ana我有MainController.js,它具有将用户的输入实时保存在本地存储中的功能。然而,我的129.html似乎没有识别出那个主控制器。如何将其添加到视图中?我见过类似ng-controller=MainController的东西,但我不确定这是否正确。

如果你使用路由器,你可以将控制器链接到视图,否则ng控制器指令是一个很好的方法。

您不能将"ng controller"指令与"ng repeat"指令相关联,因为它将为每个组调用控制器,因此您需要将所有控制器封装在父标记中,例如div:

<div ng-controller="MainController">
<div class="" ng-repeat="group in groups">
  (...)
</div>
</div>