Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - get label text for field

Question

I was wondering what the AngularJS "best practice" way of getting a label for a field is. With jQuery you just query using a "label for" query then extract the text. While it's possible to do it this way with AngularJS, something just doesn't feel right about it.

Assume you have something like this in your HTML:

<form name="MyForm" ng-controller="Ctrl">
    <label for="MyField">My spoon is too big:</label>
    <input type="text" size="40" id="MyField" ng-model="myField" />

    <br /><br />

    You entered {{ myField }} for {{ myField.label }}
</form>

The controller internal is pretty simple:

$scope.myField = 'I am a banana.';

Basically I want to populate the myField.label in the output with "My spoon is too big."

What I'm Doing Now

All I am doing right now is executing a query that pulls the data similar to the jQuery methodology ($("label[for='MyField']")). Then, if that doesn't exist I am just pulling the placeholder text. It works, but it seems like a bit of overhead.

What I'm Trying to Accomplish

I want some custom form validation and I want to include the label in the message. I just need to pull the label text so that I can write it extremely generically and then not have to worry about people switching i18n data in dynamically later in the game.

Fiddle

Per the suggested solution: https://jsfiddle.net/rcy63v7t/7/

like image 262
el n00b Avatar asked Apr 17 '15 13:04

el n00b


1 Answers

You change your HTML to the following:

<label for="MyField">{{ myFieldLabel }}</label>
<input type="text" size="40" id="MyField" ng-model="myField" />

and your JS to the following:

$scope.myFieldLabel = 'My spoon is too big:';

then later, you can get/set its value just as easily:

if ($scope.myFieldLabel === 'My spoon is too big:') {
    $scope.myFieldLabel = 'New label:';
}

Note that new AngularJS best practices call for always using a "dot" in a field reference. It would fit perfectly here if you did something like:

<label for="MyField">{{ myField.label }}</label>
<input type="text" size="40" id="MyField" ng-model="myField.value" />

and JS:

$scope.myField = {
    value: '',
    label: 'My spoon is too big:'
};

Then you can always easily access $scope.myField.label and $scope.myField.value.

like image 106
Chad Robinson Avatar answered Sep 18 '22 05:09

Chad Robinson