Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have been given a requirement to create a symbol toolbar, a toolbar where each button represents a unique symbol.

This is how the toolbar would work:

1) A user clicks inside a text field and enters data

2) The user would then click a symbol on the toolbar and it will be appended to that specific text field

3) The browser will put focus back on that text field

I have created this toolbar, but I really dislike my implementation because it feels really hacky. In my implementation, I created two functions, addSymbol and setLastFocused in my controller:

$scope.addSymbol = function (field)
{
    if (!$scope.product[$scope.lastFocusedModelKey])
    {
        $scope.product[$scope.lastFocusedModelKey] = "";
    }

    $scope.product[$scope.lastFocusedModelKey] = $scope.product[$scope.lastFocusedModelKey] + field.symbol.SymbolCharacter;

    $('#' + $scope.lastFocusedModelKey).focus();
}

$scope.setLastFocused = function (lastFocusedModelKey)
{
    $scope.lastFocusedModelKey = lastFocusedModelKey;
}

SetLastFocused is called every time a user puts focus on a text field. I pass in a string of the field name like this:

<input type="text" id="Foo" name="FooName" ng-model="product.Foo" class="form-control input-xs" ng-focus="setLastFocused('Foo')">

AddSymbol accepts the button field as a parameter, and appends the symbol to the model that is bound to the text field, and then re-focuses on the text field.

I feel like this is hacky because:

1) I have to use jQuery to re-focus on the text field.

2) I'm passing in a hardcoded string representing the field name (meaning if I change the name of the field and forget to change the hardcoded string, then this symbol feature will break for that specific text field)

This works fine now with a few text fields in which the users may want to append symbols, but now I'm learning I need to add the functionality to append symbols to text fields inside a whole Angular Ui-Grid (which exists inside a separate controller). So I am realizing I need to refactor this if I want this to work with a Ui-Grid as well. I know I need to move this code to a separate service, but I would also like to make this cleaner. I'm just not really sure how.

How can I make this code follow best Angular practices?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.