I have an angular directive for data insert. And now I want to use same angular directive for data edit/update, but my problem is, the input value is not shown in the input text field. My code is given below:
directive (js) :
dirApp.directive("inputDesign", function () {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
inputName: '#',
inputNameText: "#",
inputValue: '#',
inputObject: '=',
checkInput: '&'
},
templateUrl: '../../template/_inputDesign.php'
};
});
template _inputDesign.php:
<div class="form-group">
<!-- {{inputObject[name]}} and {{inputValue}} value is not shown -->
<input type="text" value="{{inputObject[name]}}" class="form-control" ng-model="inputObject[name]" name="{{inputName}}" placeholder="Enter {{inputNameText}}">
</div>
html code ::
<input-design
input-name="a_gradeName"
input-name-text="Grade Name"
input-value="some value" // not work
input-object="gradeTbl.gradeName"
check-input="checkInput(gradeTbl.gradeName, gradeTbl.gradeName[name])">
</input-design>
js code ::
/* grade model */
$scope.gradeTbl = {
'gradeName': {
'name': 'a_gradeName',
'a_gradeName': 'some value',
'display': 'Grade Name',
'status': 'initial',
'regExpr': 'Alphanumeric'
}
};
$scope.gradeTbl.gradeName.a_gradeName = "this is test"; // not worked
$scope.gradeTbl.gradeName.name= "this is test x";
In your _inputDesign.php, change value and ng-model from {{inputObject[name]}} to inputObject.name.
My best guess is that is has to do with this bit:
scope: {
inputName: '#',
inputNameText: "#",
inputValue: '#',
inputObject: '=',
checkInput: '&'
},
I would try changing inputValue to
inputValue: '=',
Here is another answer about the difference between = and # in scope.
What is the difference between '#' and '=' in directive scope in AngularJS?
Related
Brief intro to my problem
I have a directive that dynamically shows a list of checkboxes. It has a parameter called options that should be an array like the following, in order to show the list of checkboxes correctly. For example:
var options = [
{
id: 1,
label: 'option #1'
},
{
id: 2,
label: 'option #2'
},
{
id: 3,
label: 'option #3'
}
];
So, by passing this array to my directive, a group of three checkboxes would be shown.
Also, the directive requires ngModel that will have the result of checking/unchecking the checkboxes (this object is always passed initialized). For example:
var result = {
"1": true,
"2": true,
"3": false
};
This case means that the first and second checkboxes (options with id=1 and id=2) are checked and the third (option with id=3) is unchecked.
My directive
template.html
<div ng-repeat="option in options track by $index">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="result[option.id]">
{{ ::option.label }}
</label>
</div>
</div>
directive.js
angular
.module('myApp')
.directive('myDirective', myDirective);
function myDirective() {
var directive = {
templateUrl: 'template.html',
restrict: 'E',
require: 'ngModel',
scope: {
options: '='
},
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs, ngModel) {
scope.result;
ngModel.$render = setResult;
function setResult() {
scope.result = ngModel.$viewValue;
};
};
};
What I want to achieve
Wherever I use my directive, I want to be able to trigger a function whenever the ngModel changes. Of course, I would like to achieve this using ngChange. So far I have the following:
<my-directive
name="myName"
options="ctrlVM.options"
ng-model="ctrlVM.result"
ng-change="ctrlVM.selectionChanged()">
</my-directive>
but the .selectionChanged() function is not triggered whenever the model changes. Anyone has any idea why this is not working as I am expecting it to work?
First thing first, please try to provide jsfiddle, codepen etc code snippet link so that it will be easy for others to answer your question.
The problem in your case is that you are never updating the ctrlVM.result object as you are passing the object's reference and that reference never change even if you manually update the model by calling ngModel.$setViewValue().
To solve the problem, just update the model by manually calling ngModel.$setViewValue() and pass in the new Object so that the reference changes and that will trigger the ngChange directives logic.
I've added the logic to do that and it will successfully trigger the change. Look at the code below:
angular
.module('myApp', [])
.directive('myDirective', myDirective)
.controller('MyController', function($timeout) {
var vm = this;
vm.options = [{
id: 1,
label: 'option #1'
}, {
id: 2,
label: 'option #2'
}, {
id: 3,
label: 'option #3'
}];
vm.result = {
"1": true,
"2": true,
"3": false
};
vm.selectionChanged = function() {
vm.isChanged = true;
$timeout(function() {
vm.isChanged = false;
}, 500)
}
});
function myDirective() {
var directive = {
templateUrl: 'template.html',
restrict: 'E',
require: 'ngModel',
scope: {
options: '='
},
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs, ngModel) {
scope.result;
ngModel.$render = setResult;
function setResult() {
scope.result = ngModel.$viewValue;
};
scope.updateValue = function(val) {
ngModel.$setViewValue(Object.assign({}, val))
}
};
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<script type="text/ng-template" id="template.html">
<div ng-repeat="option in options track by $index">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="result[option.id]" ng-click="updateValue(result)">
{{ ::option.label }}
</label>
</div>
</div>
</script>
<div ng-controller="MyController as ctrlVM">
<my-directive name="myName" options="ctrlVM.options" ng-model="ctrlVM.result" ng-change="ctrlVM.selectionChanged()">
</my-directive>
<div> Data: {{ctrlVM.result}} </div>
<div> isChanged: {{ctrlVM.isChanged}} </div>
</div>
</div>
#Gaurav correctly identified the problem (ng-change is never called because the object reference does not change). Here is a simpler solution that doesn't require manually cloning into the controller's model:
Add a binding for the ng-change attribute:
scope: {
options: '=',
ngChange: '&' // Add this, creates binding to `ctrlVM.selectionChanged()`
}
Add an ng-change to your checkbox template:
<input type="checkbox"
ng-model="result[option.id]" ng-change="ngChange()">
Now, when any checkbox changes it will automatically call the outer ng-change function without the intermediate step of cloning into the model.
I am working with angular 1.5.6 component. I am trying to use the output binding ('&') but impossible to get it work. I have plunkered my issue.
Code for index.html :
<body ng-app="MyApp">
<my-view></my-view>
</body>
Code for the component for which I want to use output binding :
app.component('myInput', {
template: [
'<div class="form-group">',
'<label>{{$ctrl.label}}</label>',
'<input placeholder="{{$ctrl.placeholder}}" class="form-control" ng-model="$ctrl.fieldValue"/>',
'</div>'
].join(''),
controller: function() {},
bindings: {
label: '#',
placeholder: '#',
fieldValue: '=',
onUpdate: '&'
}
});
Code for the parent component (output binding is done with the attribute on-update):
app.component('myView', {
template: [
'<div class="container">',
' <h2>My form with component</h2>',
' <form role="form">',
' <my-input on-update="$ctrl.updateParam()" label="Firstname" placeholder="Enter first name" field-value=$ctrl.intermediaryData.firstName ></my-input>',
' </form>'
].join(''),
controller: function() {
var ctrl = this;
ctrl.userData = {
firstName: 'Xavier',
lastName: 'Dupont',
age: 25
};
ctrl.intermediaryData = {
firstName: ctrl.userData.firstName,
lastName: ctrl.userData.lastName,
age: 25
};
function updateParam(){
console.log("I have updated the component");
}
}
});
My bad, I have forgotten to put ng-change in input component. I managed to solve the issue like this :
app.component('myInput', {
template: [
'<div class="form-group">',
'<label>{{$ctrl.label}}</label>',
'<input ng-change="$ctrl.change()" placeholder="{{$ctrl.placeholder}}" class="form-control" ng-model="$ctrl.fieldValue"/>',
'</div>'
].join(''),
controller: function() {
var ctrl = this;
ctrl.change = function(){
ctrl.onUpdate();
}
},
bindings: {
label: '#',
placeholder: '#',
parentParam: '#',
fieldValue: '=',
onUpdate: '&'
}
});
I am using ngTagsInput and would like to perform some validation on my models as they change. Here is a Plunker of what I'd like to achieve.
Markup:
<div ng-repeat="field in fields">
<tags-input ng-model="field.selectedData" max-tags="{{field.maxTags}}" enforce-max-tags placeholder="{{option.placeholder}}">
<auto-complete source="updateAutocomplete($query)"></auto-complete>
</tags-input>
</div>
Fields / models:
$scope.fields = [
{
name: 'assay',
placeholder: 'Select one assay...',
maxTags: 1,
selectedData: [] // These are the models
},
{
name: 'cellLines',
placeholder: 'Select cell line(s)...',
maxTags: 5,
selectedData: []
},
...
]
Finally, my enforceMaxTags directive:
.directive('enforceMaxTags', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.push(function(value) {
console.log('link called');
});
}
};
})
The enforceMaxTags directive is being compiled, but the link function is not called even when the models change. The data binding does appear to work, though, because if I console.log the selectedData on form submission, it is filled with the correct objects. What am I missing?
Thanks in advance.
As an example of what I want, consider the following example
<select ng-options="option.text for option in options"></select>
In my directive I want to use something similar to ngOptions, because I need to create a list
For example, assume I have a directive barFoo, called as follows:
<bar-foo options="options"></bar-foo>
with a template/html as follows:
<ol>
<li ng-repeat="option in options" ng-bind="option.text"></li>
</ol>
What is needed to change all this into a call like
<bar-foo options="option.text for option in options"></bar-foo>
The main reason I need this is because I don't know the property name holding the label text (in this case it is text)
I provided a fiddle and see whether this helps. Instead of passing in "options.text for option in options", I set it up such that you pass the "options" array and then the field you want. I assumed the field will be set up as a variable; if it hard-coded, then you can just do field='someFieldName' instead.
http://jsfiddle.net/y376K/1/
HTML
<body ng-app='testApp'>
<div ng-controller='TestCtrl'>
<bar-foo options='options' field='{{optionsField}}'></bar-foo>
</div>
</body>
JS
angular.module('testApp', [])
.controller('TestCtrl', function($scope) {
$scope.options = [
{
text: 'Node.js rocks my socks',
language: 'Node.js',
},
{
text: 'Angular is hot',
language: 'Angular.js',
},
{
text: 'Backbone.js is mmmm',
language: 'Backbone.js',
}
];
$scope.optionsField = 'text';
})
.directive('barFoo', function() {
return {
restrict: 'E',
scope: {
options: '=',
field: '#'
},
template: '<ol><li ng-repeat="option in options" ng-bind="option[field]"></li>'
};
})
You can do this by parsing the attribute. The other solution would be to pass it as two attributes (see the other answer)
You should probably use a regexp for this, but I coded this quickly:
app.directive('barFoo',function($parse) {
return {
restrict: 'E',
scope: {},
templateUrl: "template.html",
link: function(scope,element,attrs) {
var splitOptions = attrs.options.split(' for ');
scope.fieldName = splitOptions[0].split('.')[1];
var repeatExp = splitOptions[1];
scope.valueName = repeatExp.split(' in ')[0];
var collectionName = repeatExp.split(' in ')[1];
scope.values = $parse(collectionName)(scope.$parent);
}
};
});
See this plnkr
I am trying create a wrapper directive over select and I am trying to assign the 'name 'attribute to the select
directive
<form name=myform>
<selectformfield label="Select Orders" id="id_1" name="orderselection"
selectedval="obj.order" options="Orders" />
</form>
I have my directive defined as
mainApp
.directive(
'selectformfield',
function() {
return {
restrict : 'E',
transclude : true,
scope : {
label : '#',
id : '#',
selectedval : '=',
options : '=',
name: '='
},
template : "<select class='form-control' ng-model='selectedval' name='{{name}}' ng-options='item as item.name for item in options' required><option value=''>-- select --</option></select>"
};
});
I am trying to access the select's name attribute through myform in the controller something like console.log($scope.myForm.orderselection) and I get undefined
If I hardcode the name in the directive then I am able to access the attribute console.log($scope.myForm.orderselection)
I am missing anything here. Do I have to do any post compile or something ?
Khanh TO is correct in that you need to setup your name correctly when trying to access to through your isolated scope. Here is a working example of what I believe you are trying to accomplish. I've added comments to the code where I've changed what you had.
plunker
Javascript:
var app = angular.module('plunker', [])
.controller('MainCtrl', function ($scope, $log) {
$scope.model = {
person: {
name: 'World'
},
people: [{
name: 'Bob'
}, {
name: 'Harry'
}, {
name: 'World'
}]
};
})
.directive('selectformfield', function ($compile) {
return {
restrict: 'E',
replace: true, // Probably want replace instead of transclude
scope: {
label: '#',
id: '#',
selectedval: '=',
options: '=',
name: '#' // Change name to read the literal value of the attr
},
// change name='{{ name }}' to be ng-attr-name='{{ name }}' to support interpolation
template: "<select class='form-control' ng-model='selectedval' ng-attr-name='{{name}}' ng-options='item as item.name for item in options' required><option value=''>-- select --</option></select>"
};
});
HTML:
<body ng-controller="MainCtrl">
<p>Hello {{ model.person.name}}!</p>
<form name='myForm'>
<label for='orderselection'>Say hello to: </label>
<selectformfield label="Select Orders" id="id_1" name="orderselection"
selectedval="model.person" options="model.people"></selectformfield>
<p ng-class='{valid: myForm.$valid, invalid: myForm.$invalid }'>The form is valid: {{ myForm.$valid }}</p>
<p ng-class='{valid: myForm.orderselection.$valid, invalid: myForm.orderselection.$invalid }'>The people select field is valid: {{ myForm.orderselection.$valid }}</p>
</form>
</body>
CSS:
.valid {
color: green;
}
.invalid {
color: red;
}
Accessing the DOM directly in $scope is bad practice and should be avoided at all costs. In MVC structure like angular, instead of accessing the DOM (view) to get its state and data, access the models instead ($scope). In your case, you're binding the name of your directive to the orderselection property of your parent scope. Also notice that a form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute. In your case, you create a new property on the parent scope.
You could try accessing the name like this if you're in your parent scope:
console.log( $scope.myform.orderselection );
Or if you're in your directive scope.
console.log( $scope.name);
Because your scope directive name property binds to your parent scope orderselection property, you need to assign a value to your parent scope property or it will be undefined. Like this:
$scope.myform.orderselection = "orderselection ";
If you need to do validation inside your directive, since you already bind the name attribute with the orderselection. You could do it like this:
template : "<select class='form-control' ng-attr-name='{{name}}' ng-disabled='[name].$invalid' .../>