Recently, I've been tackling a project that involves using a directive. Initially, everything was smooth sailing as I had my directive set up to bind to ngModel. However, I hit a roadblock when I needed to bind multiple values. Upon making the necessary changes to bind both value and staticValue, I found that the scope variable assigned to this became undefined. Check out the revised code below:
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>