My situation involves a variety of inputs, each with specific directives:
<input mask-value="ssn" validate="checkSsn"/>
<input mask-value="pin" validate="checkPin"/>
These properties are managed in the controller:
app.controller("Ctrl", ['$scope', function ($scope) {
$scope.ssn = "";
$scope.pin = "";
$scope.checkSsn = function () { /* validate $scope.ssn */ };
$scope.checkPin = function () { /* validate $scope.pin */ };
}]);
Next, we have the maskValue
directive:
app.directive("maskValue", function () {
return function (scope, element, attrs) {
/* performs focus/blur actions and string manipulation */
scope[attrs.maskValue] = this.value;
scope[attrs.validate]();
};
});
The current setup works, but it appears to be an inefficient use of Angular. It might be better to utilize an isolated scope like so:
scope: {validate: "&"}
This way, I could call scope.validate()
rather than scope[attrs.validate]()
. However, using an isolated scope prevents me from updating the corresponding value in the controller. Even setting {maskValue: "="}
doesn't work as intended because it tries to update the parent's property instead. Using {ssn: "="}
seems promising, but then I would only update a specific property of the controller, making the directive less flexible. Using $parent
is also not recommended.
How can I dynamically access controller properties within an isolated scope directive?
- Working example code: http://jsfiddle.net/MmyvX/
- Attempt to achieve desired outcome (not working): http://jsfiddle.net/MmyvX/1/
EDIT: Using ng-model=ssn
, etc. on the inputs is not viable because the actual input value changes during the focus/blur events in mask-value
. For instance, it may be transformed to *****####
, but the original value #########
needs to be stored somewhere for later use, preferably in the controller.