AngularJS中ng-click上的ng-include

4
我希望找到一种将经过控制器优化的 HTML 插入警报框中的方法。但是我无法找到这样的方法...
<script type="text/ng-include" id="login.html">
       <form data-select="exeption" class="loginBox shadowed" onclick="event.stopPropagation();" novalidate name="login">
        <h2>Login alert</h2>
            <!--inputs and such, they need to be controlled by the controller-->
    </form>
</script>
<script type="text/ng-include" id="bug.html">
    <form data-select="exeption" class="bugBox shadowed" onclick="event.stopPropagation();" novalidate name="report">
        <h2>Bug report</h2>
            <!--inputs and such, they need to be controlled by the controller-->
    </form>
</script>

这两个模板应该由JS自己或用户调用。这些模板应该进入这个div,但是我不能使用innerHTML,因为在模板中有一些ng-models和类似的东西...
<div id="alert" data-ng-click="empty()" data-ng-controller="alert" role="navigation"></div>
1个回答

10

通常我会使用ng-if/ng-show。我不确定我是否正确理解了你的请求,所以我将写一个简单的示例;假设你有一个简单的登录表单:

<form>
  <label>
    username:
    <input name="username" type="text" ng-model="username"/>
  </label>
  <label>
    password:
    <input name="password" type="password" ng-model="password"/>
  </label>
  <button type="submit" ng-click="login()">login</button>
  <div class="message" ng-if="message">
  </div>
</form>

在控制器内部:

$scope.username = '';
$scope.password = '';

$scope.message = '';

$scope.login = function() {
  // login example function with ajax request and success/error promises
  myLogin($scope.username, $scope.password)
    .success(function() {
      $scope.message = 'Logged in!';
    })
    .error(function(errorMessage) {
      $scope.message = errorMessage;
    })
}

这种方法可以确保当 $scope.message 为空时,你的div也是空的,只需给 $scope.message 赋值就可以自动显示它。 如果你需要使用 ng-include,最简单的方法就是将它放在一个需要时才显示的div内:

<div ng-if="showMessage">
  <div ng-include="template.html"/>
</div>

更新:根据我之前的示例,如果你想为每种情况包含不同类型的消息,可以使用多个ngIf,包括不同的模板;例如:

<div ng-if="showMessage">
  <div ng-if="message.type == 'alert'" ng-include="'alert.html'"/>
  <div ng-if="message.type == 'info'" ng-include="'info.html'"/>
  <div ng-if="message.type == 'warning'" ng-include="'warning.html'"/>
  <div ng-if="message.type == 'error'" ng-include="'error.html'"/>
</div>

这种方式还可以使用ngInclude来实现登录表单或其他类型的弹出窗口。

更新2:与上一个示例相同,但使用另一种解决方案:

<div ng-if="showMessage">
  <div ng-include="templatePath"/>
</div>

然后您可以在控制器中将整个路径提供给局部视图:

$scope.templatePath = 'alert.html';

好的,你可以使用基本的if-then结构;我更新了我的答案以更好地解释我的意思。 - Polmonite
1
这可能可行,但它似乎非常奇怪。Angular没有重新解析HTML的能力吗? - Akxe
你也可以使用ng-include="template",其中$scope.template = 'whole/path/to/partial.html';。个人而言,我不喜欢在js模型中放置模板路径,因为如果我更改了一个模板,我必须更改所有控制器(除非它们在angular指令内:在这种情况下没问题)。已更新答案。 - Polmonite
这些是页面模板,如果有任何更改...顺便问一下:如果我将templatePath更改为空,真的需要那个if吗? - Akxe
无法使其工作...https://student.sps-prosek.cz/~eisead11it/web/IS/Student/#/(下面有报告错误按钮)顺便说一句,非常感谢所有的努力。 - Akxe
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接