问题描述
我想知道获取字段标签的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.';
基本上,我想用"我的勺子太大."
我现在所要做的就是执行一个查询,该查询提取类似于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/
Per the suggested solution: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-获取字段的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!