Search code examples
javascriptangularjsdotnetnuke

AngularJS form in develop module of dotnetnuke 7


I'm developing a dotnetnuke 7 module using AngularJS. Here is my code in View.ascx:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<h2>Validation Example</h2>

<form  ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>

<p>Username:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Username is required.</span>
  </span>
</p>

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Email is required.</span>
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>
  </span>
</p>

<p>
  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script>
    var app = angular.module('myApp', []);
    app.controller('validateCtrl', function ($scope) {
        $scope.user = 'John Doe';
        $scope.email = '[email protected]';
    });
</script>

The code is copied from W3School but it seems that the AngularJS is not working well. Here is my View's screenshot: enter image description here

I have tried an AngularSJ simple example and it working good likes:

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

enter image description here

Why is my first block of code not working? Are there any issues regarding the "form" tag in my module?


Solution

  • The form tag is certainly an issue when running within DNN/ASP.NET Webforms. I did a tutorial on DNNHero.com on building Angular applications as DNN modules.

    Two pieces of advice:

    1. Use a div tag to add your angular controller directives:

    <div id="userForm" ng-controller="validateCtrl" ng-init="init(<%=this.ModuleId%>)">

    1. Don't hard-code the ng-app directive in your html. Instead use the bootstrap method for attaching your app.

    <script type="text/javascript"> angular.element(document).ready(function () { var moduleContainer = document.getElementById('userForm'); angular.bootstrap(moduleContainer, ["myApp"]); }); </script>