I'm trying to figure out where and how to use directives in angularjs. I have several pages with lots of input fields and each time I want to add some conditional ng-class and a button that only shows in certain conditions. A rough example can be seen at:
Now I'd like to type less and hope that directives can help me. The following code does not work, but maybe it shows where I want to go:
this is how I'd like to type my html:
<tr>
<td>First Name:</td>
<td>
<dirty-input attr="firstName"/>
</td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<dirty-input attr="lastName"/>
</td>
</tr>
so I tried to accomplish this with following controller:
app.controller('PersonController', function($scope) {
$scope.person = {firstName: 'John', lastName: 'Doe'};
$scope.personEdited = {firstName: $scope.person.firstName, lastName: $scope.person.lastName};
$scope.firstName = {objName: 'person', editedObject: 'personEdited', attrName: 'firstName'};
$scope.lastName = {objName: 'person', editedObject: 'personEdited', attrName: 'lastName'};
});
and this directive:
app.directive('dirtyInput', function() {
return {
restrict: 'E',
scope: {
attr: '=attr',
},
template: '<input type="text" ng-model="{{attr.editedObject}}.{{attr.attrName}}"/>'
};
});
This can be seen at: JSFiddle with directives (not working)
Obviously, this doesn't work. Am I trying to do something that isn't possible or am I just doing it wrong?