AngularJS - get label text for field

為{幸葍}努か 提交于 2019-12-05 08:57:44

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.

Let's say in your controller you have a scope variable like

$scope.myField = {};
$scope.myField.label = "Fruit name";

and your template is like

<form name="MyForm" ng-controller="Ctrl">
    <label for="MyField">{{myField.label}}</label>
    <input type="text" size="40" id="MyField" ng-model="myField.value" />
    <br /><br />
    You entered {{ myField.label }} for {{ myField.label }}
</form>

By this field label will come dynamically. Apply custom validation in input field as per your requirement.

Hope I understand exactly what you wants.

Just put your label text in the input title and you can use a "#" directive. You can also use this to make sure the label id matches.

<label for="{{myfield_control.id}}">{{myfield_control.title}}</label>
<input type="text" size="40" id="MyField" ng-model="myField" title="My spoon is too big:" #myfield_control >

<br /><br />

You entered {{ myField }} for {{ myfield_control.title }}

myField is your ngModel. myfield_control is a reference to your input control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!