AngularJS - 获取字段的标签文本 [英] AngularJS - get label text for field

查看:38
本文介绍了AngularJS - 获取字段的标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道获取字段标签的 AngularJS最佳实践"方法是什么.使用 jQuery,您只需使用标签"查询然后提取文本即可.虽然可以使用 AngularJS 以这种方式做到这一点,但总感觉有些不对劲.

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.

假设您的 HTML 中有这样的内容:

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>

控制器内部非常简单:

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

基本上我想在输出中填充 myField.label我的勺子太大了."

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

我现在所做的就是执行一个查询,该查询类似于 jQuery 方法($("label[for='MyField']"))提取数据.然后,如果那不存在,我只是拉占位符文本.它有效,但似乎有点开销.

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.

我想要一些自定义表单验证,并且我想在消息中包含标签.我只需要拉标签文本,这样我就可以非常通用地编写它,然后不必担心人们在游戏后期动态切换 i18n 数据.

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.

根据建议的解决方案:https://jsfiddle.net/rcy63v7t/7/

推荐答案

您将 HTML 更改为以下内容:

You change your HTML to the following:

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

和你的 JS 如下:

$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:';
}

请注意,新的 AngularJS 最佳实践要求在字段引用中始终使用点".如果您执行以下操作,它将非常适合此处:

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" />

和JS:

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

然后您可以随时轻松访问 $scope.myField.label$scope.myField.value.

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

这篇关于AngularJS - 获取字段的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆