javascript - AngularJS ng-template with ng-messages-include

标签 javascript html angularjs

我正在尝试创建一个脚本类型的 text/ng-template 以将我的错误消息模板放入 $templateCache 中。我希望这个脚本文件是远程的,在 HTML 之外的它自己的文件中。

<script type="text/ng-template" id="error-messages">
  <span ng-message="required">This field is required.</span>
  <span ng-message="min">This number must be larger than {{min}}.</span>
  <span ng-message="max">This number must be smaller than {{max}}.</span>
  <span ng-message="number">A number is required.</span>
  <span ng-message="date">A date is required.</span>
</script>

然后在 HTML 中我想引用这个我认为应该在 $templateCache 中的模板,我可以通过 Id 访问它。

<form name="userForm">       
      <div class="form-group">
        <label for="requiredInput">Required</label>
        <input type="text" class="form-control" id="required" name="requiredInput" 
        ng-model="user.required" required />
        <div ng-messages="userForm.requiredInput.$error" ng-messages-include="error-messages"></div>
      </div>
</form>

如果我将脚本与 HTML 内联,它就可以正常工作,但我希望它位于远程文件中。当我将它移动到远程文件时,我的 HTML 无法找到我的模板错误消息。

这是我分享的第一个 Plunker。如果您无法访问,请告诉我。 http://plnkr.co/edit/NgSm7piaECWBab1LOmp3?p=preview

最佳答案

请检查plunker - http://plnkr.co/edit/luhUuZURCOeHSuEhi11x?p=info

angular.module('app', ['ngMessages'])
.run(function ($templateCache, $http) {
  $http.get('scriptTemplate.html')
  .then(function(response) {
    $templateCache.put('error-messages', response.data); 
  })
})

在应用程序的运行阶段使用 $http 加载 ng-messages-include 模板并将其保存在模板缓存中。

关于javascript - AngularJS ng-template with ng-messages-include,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28678878/

相关文章:

javascript - 如何使用循环使用 Javascript 更改 div id

javascript - Drupal Theming js 错误 - 无法读取未定义的属性 'top'

javascript - 访问 Controller 函数内的元素内部 html 和属性值

json - MarkLogic 7 REST API - 错误请求错误

javascript - 如何在 Angular js 中获取特定货币符号(在我的例子中是卢比符号)而不是默认货币符号(美元 $ 符号)

javascript - 无法使用 jquery 选择器访问 svg/xml 路径元素中的数据?

javascript - 返回部分 View 和消息

javascript - 原型(prototype)对象和对象数组

javascript - 我可以使用 execCommand 撤消来撤消不是使用 execCommand 执行的操作吗?

javascript - 通过点击获取div id