AngularJS双向绑定返回未定义

时间:2016-09-07 20:44:39

标签: javascript angularjs binding directive

我正在开发一个需要使用指令的项目,我的指令工作绑定到ngModel但我意识到我需要绑定多个值,当我更改我的代码绑定值和staticValue时,指定的范围变量现在这是未定义的。以下是我的代码,

var app = angular.module('fieldSelectCheck', []);
app.directive('fieldSelectCheck', function () {

    var controller = ['$scope', function ($scope) {

        $scope.checkBoxClick = function () {
            if ($scope.isChecked === true) {
                $scope.fieldToggle = true;
            } else {
                $scope.fieldToggle = false;
                $scope.staticValue = "";
            }
        };

    }],

    url = 'Custom/BSI_iMIS_Importer/App/Directives/fieldSelectCheck.html';

    return {
        restrict: 'EA',
        templateUrl: url,
        scope: {
            fieldName: '@',
            fieldText: '@',
            options: '=',
            checkBoxClick: '@',
            isChecked: '@',
            fieldToggle: '=?bind',
            value: '=',
            staticValue: '='
        }, 
        controller: controller
    };
});

HTML模板

<div class="form-group row" data-ng-app="app">
    <label for="{{fieldName}}" class="col-lg-2 form-control-label text-right">{{fieldText}}</label>
    <div class="col-lg-3" data-ng-hide="fieldToggle">
        <select class="form-control" name="{{fieldName}}" data-ng-model="value" data-ng-options="option for option in options">
            <option value="">-- Please Select A Field --</option>
        </select>
    </div>
    <div class="col-lg-3" data-ng-show="fieldToggle">
        <input class="form-control" type="text" data-ng-model="staticValue" />
    </div>
    <div>
        <input type="checkbox" data-ng-model="isChecked" data-ng-change="checkBoxClick()" /> Static Value
    </div>
</div>

指令的实施

<field-Select-Check 
    field-Name="{{fields}}" 
    field-Text="{{fields}}" 
    value="test" 
    static-Value="$parent[fields].staticValue"
    options="userFields"
    ng-repeat="fields in nameFields">
</field-Select-Check>

1 个答案:

答案 0 :(得分:0)

将自定义指令与ng-repeat指令分开。自定义指令创建隔离范围。 ng-repeat指令期望继承范围。

<div ng-repeat="fields in nameFields">
    <field-select-check 
        field-name="{{fields}}" 
        field-next="{{fields}}" 
        value="test" 
        static-value="valueList[fields]"
        options="userFields">
    </field-Select-Check>
</div>