Jamie Jamie - 3 months ago 20
AngularJS Question

AngularJS Two Way Binding Returns Undefined

I am working on a project which requires the use of a directive, I had my directive working binding to ngModel but I realized I need to bind multiple values, when I changed my code to bind value and staticValue the scope variable assigned to this is now undefined. Below is my code,

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 Template

<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>


Implementation of Directive

<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>

Answer

Separate custom directive from the ng-repeat directive. The custom directive creates isolate scopes. The ng-repeat directive expects inherited scope.

<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>