繁体   English   中英

AngularJS ng-包括ng-click

[英]AngularJS ng-include on ng-click

我想找到一种方法将HTML(为控制器优化)插入警报div。 但是我找不到办法做到这一点......

<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模型和类似的东西......

<div id="alert" data-ng-click="empty()" data-ng-controller="alert" role="navigation"></div>

通常我所做的是使用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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM