Search code examples
angularjsangularjs-directiveangularjs-scope

Use a directive to display scope value and update scope


I have an array of vertex values that I loop over and display to the user. The values are stored as a space delimited string, like this:

vrtx = ["10.3 20.3 10.5", "13.2 29.2 3.0", "16.3 2.3 20.2", ...] 

I want to provide a friendly interface to the user to edit the values. This requires me to split the strings into three separate numbers and put them into three individual inputs.

I want to create a directive, as I am not able to store the values as separate values, but after the editing is done, I want to join the values back and update the scope to store the new values as strings.

This is the directive I have so far:

 myApp.directive('fieldValue', function () {

    return {
        scope: {
          field:'='
        },
        link: function (scope, element, attrs) {
            var fields  = scope.field.split(' ');
            element.html("<input type='number' value='"+ fields[0] +"' class='vertex-input'/><input type='number' value='"+ fields[1] +"' class='vertex-input'/><input type='number' value='"+ fields[2] +"' class='vertex-input'/>");    
        }
    }

});

This splits the value and shows the three inputs with the individual values, but my question is how do I join these values and save them back to the scope? Any suggestions would be greatly appreciated! TIA


Solution

  • You could use formatters/parsers to achieve what you want, but you may have to adjust your input to use ngModel, and I'm not quite sure how it would work with 3 separate input fields:

    myApp.directive('fieldValue', function () {
    
        return {
            scope: {
              field:'='
            },
            require: 'ngModel',
            link: function (scope, element, attrs, ngModel) {
                var fields  = scope.field.split(' ');
                element.html("<input type='number' value='"+ fields[0] +"' class='vertex-input'/><input type='number' value='"+ fields[1] +"' class='vertex-input'/><input type='number' value='"+ fields[2] +"' class='vertex-input'/>");
    
                ngModel.$formatters.push(function(value){
                  //return the value as you want it displayed
                });
    
                ngModel.$parsers.push(function(value){
                  //return the value as you want it stored
                });
    
    
            }
        }
    
    });
    

    This way gives you a lot more flexibility in my opinion to use any strategy you want. Read more about it here: https://alexperry.io/angularjs/2014/12/10/parsers-and-formatters-angular.html

    And, more official docs here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController