AngularJS ng-include on ng-click

I would like to find a way to embed HTML (which is optimized for the controller) in the alert div. However, I could not find a way to do this ...

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

These two patterns must be invoked by JS itself or by the user. These templates should fall into this div, but I can’t use innerHTML, because the templates have some ng models and such things ...

<div id="alert" data-ng-click="empty()" data-ng-controller="alert" role="navigation"></div>
+4
source share
1 answer

I usually use ng-if / ng-show. I'm not sure I understood your request correctly, so I’ll write a small example; let's say you have a simple login form:

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

Inside the controller:

$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;
    })
}

, div , $scope.message , , $scope.message . ng-include, , , div, , :

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

UPDATE:, , , 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';
+10

Source: https://habr.com/ru/post/1535343/


All Articles