I am learning angularjs and working on a single page application using the ng-view. Unfortunately, my partial views won't load into my index.cshtml. Instead they load as a separate page. Below is my code:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div ng-app="employeeInfoApp" ng-controller="employeeCtl">
<div class="col-sm-4">
<!--Example of a Dropdown List-->
<select ng-model="employeeinfo.EmpName" ng-options="employeeinfo.EmpName for employeeinfo in EmployeeInfoes">
<option value="">-- Please Select A Client Company --</option>
</select>
<p></p>
<!-- Example of Table of Data-->
<table>
<thead>
<tr>
<th>Emp Name</th>
<th>Dept Name</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="emp in EmployeeInfoes">
<td>{{emp.EmpName}}</td>
<td>{{emp.DeptName}}</td>
<td>{{emp.Designation}}</td>
</tr>
</tbody>
</table>
<p></p>
Add Employee
<div ng-view class="container"></div>
</div>
</div>
</body>
</html>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/LegalScripts/legalServices.js"></script>
<script>
//Name the module
var app = angular.module('employeeInfoApp', ['ngResource', 'legalServices', 'ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/addemp', {
templateUrl: 'AddEmp.cshtml',
controller: 'EmployeeInfoController'
}).
otherwise({
redirectTo: '/home'
});
}]);
//Add the controller
app.controller("employeeCtl", ["$scope", "EmployeeInfo", function ($scope, EmployeeInfo) {
$scope.EmployeeInfoes = EmployeeInfo.query();
$scope.SelectedEmployeeInfo = {};
}]);
</script>
You can't load .cshtml file directly from its path you need to load it from MVC controller action as it contains razor which which should be parsed using MVC Razor view engine likewise suppose you had Employee controller that will contain an action AddEmp that will return a view indirectly using c#
App.js
$routeProvider.
when('/addemp', {
templateUrl: 'Employee/AddEmp', //you need to call controller action
controller: 'EmployeeInfoController'
}).
The issue here is that I was using Angular 1.4 (which visual studio nuget package manager automatically installs.)
Routing in Angular 1.4 has been changed to accommodate using multiple views (and components) but the old ng-view directive won't work. See this Introduction to Routing in 1.4
http://www.codeproject.com/Articles/891436/Introduction-to-Basics-of-Angular-newRouter
My quick fix solution was to download the Angular 1.3 scripts library into my project. Then my partial views worked fine.
Related
With my Laravel project I'm using MDBootstrap to style a datatable. However, when running the following script at the bottom of my page to create the datatable, the included Search function and the pagination do not get styled and do not get classes added to them. The "Show Entries" button at the top left also does not get styled by MDB. Looking at the first example on Bootstrap webpage, the search function gets styled automatically and the pagination get styled with buttons with the same scripts and styling that I have included. Do you see anything that I could be missing?
// Material Design example
$(document).ready(function () {
$('#dtBasicExample').DataTable({
"order": [[ 1, "asc" ]]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
index.blade.php
#extends('layouts.app')
#section('content')
<div class="float-left">
<a href="/" class="btn btn-light-blue">
<i class="fa fa-arrow-left" aria-hidden="true"></i>
</a>
</div>
<table id="dtBasicExample" class="table" width="100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
#endsection
#section('scripts')
<script src="{{asset('js/jquery.min.js')}}"></script>
<script src="{{asset('js/popper.min.js')}}"></script>
<script src="{{asset('js/bootstrap.min.js')}}"></script>
<script src="{{asset('js/datatables2.min.js')}}"></script>
<script>
// Material Design example
$(document).ready(function () {
$('#dtBasicExample').DataTable({
"order": [[ 1, "asc" ]]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
#endsection
app.scss
// Fonts
#import url('https://fonts.googleapis.com/css?family=Nunito');
#import url('https://use.fontawesome.com/releases/v5.11.2/css/all.css');
// Bootstrap
//#import '~bootstrap/scss/bootstrap';
// MDBootstrap
#import '~mdbootstrap/css/bootstrap.min.css';
#import '~mdbootstrap/css/mdb.min.css';
#import '~mdbootstrap/css/addons/datatables2.min.css';
//Awesome Font
#import '~font-awesome/css/font-awesome.min.css';
app.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{asset('css/app.css')}}">
<title>Datatable Test</title>
</head>
<body>
<div class="container">
<br>
#include('inc.messages')
#yield('content')
</div>
<script src="{{asset('js/app.js')}}"></script>
#yield('scripts')
</body>
</html>
bootstrap.js
window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
// require('bootstrap');
require('./../../node_modules/mdbootstrap/js/jquery.min.js');
require('./../../node_modules/mdbootstrap/js/popper.min.js');
require('./../../node_modules/mdbootstrap/js/bootstrap.min.js');
require('./../../node_modules/mdbootstrap/js/mdb.min.js');
require('./../../node_modules/mdbootstrap/js/addons/datatables2.min.js');
} catch (e) {}
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
webpack.mix.js
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.js('node_modules/mdbootstrap/js/jquery.min.js', 'public/js')
.js('node_modules/mdbootstrap/js/popper.min.js', 'public/js')
.js('node_modules/mdbootstrap/js/bootstrap.min.js', 'public/js')
.js('node_modules/mdbootstrap/js/addons/datatables2.min.js', 'public/js');
Turns out it was more scripting that was missing for styling. After including the following script after my scripts and before the DataTable function at the bottom of index.blade.app created the styling I was looking for.
<!-- Datatable Scripts -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script>
I've developed a simple web page with angularjs and spring framework.
I tried to make the web page using angular route so that web page work as SPA.
Here's my simple main jsp file. The page is shown when I access to 'http://localhost:8080/test' on the chrome.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page session="false" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.min.js"></script>
<script>
angular.module("app", ['ngRoute'])
.config(function($routeProvider) {
$routeProvider.when("/home", {
templateUrl: "home.html",
controller: "controller"
})
})
.controller("controller", function() {
});
</script>
</head>
<body ng-app="app" ng-controller="controller as main">
<ul>
<li>HOME</li>
</ul>
<ng-view></ng-view>
<div ng-view></div>
</body>
</html>
I want to put the home.html into <ng-view> or <div class="ng-view"> when I click the 'HOME' link without page refresh but it's not working.
What's the problem with the code?
To get it to work change href="#/home" to href="#!home"
Also, make sure home.html is in the /src/main/resources/static/ directory
I would prefer to use .html with Thymeleaf instead of .jsp
Read
Integrating JSP with AngularJS, Is it a concern in real world...Beginer in Angular JS
https://spring.io/blog/2015/08/19/migrating-a-spring-web-mvc-application-from-jsp-to-angularjs
Upon submission of a form, I want to push that data to my Firebase db and so I'm creating a function to do so (addMeeting). However, upon pressing the button to submit I get the error:
TypeError: undefined is not a function
at l.$scope.addMeeting (http://localhost:8000/js/controllers/meetings.js:10:12)
meetings.js:10:12 is right where my $push is if you'll look at my code below.
My HTML:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Angular Data</title>
<meta name="viewport" content="width=device-width, userscalable=no">
<link rel="stylesheet" href="css/style.css">
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/lib/angular/angular-route.min.js"></script>
<script src="js/lib/angular/angular-animate.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/registration.js"></script>
<script src="js/controllers/meetings.js"></script>
</head>
<body>
<header>
<nav class="cf" ng-include="'views/nav.html'"></nav>
</header>
<div class="page">
<main class="cf" ng-view></main>
</div>
</body>
</html>
My apps.js:
var myApp = angular.module('myApp',
['ngRoute', 'firebase', 'appControllers']);
var appControllers = angular.module('appControllers', ['firebase']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
controller: 'RegistrationController',
templateUrl: 'views/login.html'
}).
when('/register', {
controller: 'RegistrationController',
templateUrl: 'views/register.html'
}).
when('/meetings', {
controller: 'MeetingsController',
templateUrl: 'views/meetings.html'
}).
otherwise({
redirectTo: '/login'
});
}])
meetings.js -the Controller containing the addMeeting function that is failing:
myApp.controller('MeetingsController',
function($scope, $firebaseObject) {
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseObject(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
}); //MeetingsController
The view that is calling that function upon submission of a form:
<section class="meetings cf">
<h1>Add Meetings</h1>
<form class="formgroup addmeeting cf"
name="myform"
ng-submit="addMeeting()"
novalidate>
<div class="inputwrapper">
<input type="text" name="meetingname" placeholder="Meeting Name"
ng-model="meetingname" ng-required="true">
</div>
<button type="submit" class="btn"
ng-disabled="myform.$invalid">+</button>
</form>
<h2>Your Meetings</h2>
<div class="meeting" ng-repeat="meeting in meetings">
<p>{{meeting.name}}</p>
</div>
</section>
**Edit: ** It has something to do with the .push() method itself. I see that in the latest version of angularfire/firebase it should be .push, instead of .$push, ad have changed that but it does not solve my problem. I reverted AngularFire and Firebase to versions 0.8.2 and 1.0.21 respectively, re-introduced the .asObject() and $push, and everything works fine. I don't understand why .push() is failing with all the latest (Firebase 2.2.2, AngularFire 1.0).
Firebase's AngularFire library has two primary types: $firebaseObject and $firebaseArray (instantiated through $asObject and $asArray respectively in pre-1.0 versions of AngularFire).
You're using both the wrong type and the wrong method. To quote AngularFire's documentation on its array type:
Synchronized arrays should be used for any list of objects that will be sorted, iterated, and which have unique IDs. The synchronized array assumes that items are added using $add(), and that they will therefore be keyed using Firebase push IDs.
So:
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseArray(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$add({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
You made a typo, it should be .push instead of $push
CODE
$scope.addMeeting = function() {
meetings.push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
Reference
Since I'm using Web Application having NuGet Package's Microsoft.AspNet.Razor installed.
In WebForm pages (.aspx), I can use ResolveUrl() but in Razor pages (.cshtml), I get this error -->
"x:\Source\Foo.Dealer\Foo.Dealer.WebApp.Mobile\Member\DmsDashboard.cshtml(103): error CS0103: The name 'Url' does not exist in the current context"
Source-Code here..
#section HeadJavascriptLibraryFile
{
<script type="text/javascript" src="#Url.Content("~/scripts/webpages/setting-dmsdashboard.js")"></script>
}
and
<img src="#(Url.Content("~/images/miscellaneous/reportandpiechart2.png"))" alt="" />
Source Code as requested...
//LayoutMembmerGeneral.cshtml
#using Foo.Dealer.WebApp.Mobile.Infrastructure;
#{
if (LoginManagementTools.DealerUserLoginValidation_BrowsingPage(HttpContext.Current.Request, HttpContext.Current.Response, HttpContext.Current.Session) == false) { }
}<!DOCTYPE html>
<html>
<head>
<title>#Page.Title</title>
#RenderSection("HeadJavascriptLibraryFile", false)
</head>
<body>
#RenderBody()
</body>
</html>
//DmsDashboard.cshtml...
#using Foo.Dealer.WebApp.Mobile.Infrastructure
#using System.Web.Mvc;
#{
Page.Title = "A New Dawn In Auto Pricing";
Layout = "LayoutMemberGeneral.cshtml";
}
#section HeadJavascriptLibraryFile
{
}
<div id="WebLayout1">
<img src="#Url.Content("images/miscellaneous/reportandpiechart2.png")" alt="" />
</div>
The URL helper doesn't seem to exist in ASP.Net Web Pages (which is essentially what you are attempting to do), but you can simply use the following code to achieve the same effect:
<img src="~/images/miscellaneous/reportandpiechart2.png" alt="" />
The tilde (~) references the application root and is transformed when the page is compiled and sent to the client.
The tilde (~) is not transformed as part of any data- attributes and likely, other places also, though I haven't researched extensively.
If you happen to need this information in a place where the automatic transofmration isn't working, you can use the tilde equivalent, HttpContext.Current.Request.ApplicationPath.
In most Razor views, you should be able to shorten it to the following:
#Request.ApplicationPath
Reference: http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx
Another alternative in some situations is to use the VirtualPathUtility such as:
#VirtualPathUtility.ToAbsolute("~/")
Telerik's TreeView control, although fancy and with a lot of functionality is proving to be a nightmare for me now. However I could not find a better TreeView control which supports collapsing/expanding etc. and has a little bit of documentation. Here's my problem.
This is the site master : _Layout.cshtml
<!DOCTYPE HTML>
<html>
<head>
<title>#ViewBag.Title</title>
<!--
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/custom.css")" rel="stylesheet" type="text/css" />-->
#(Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group =>
group.Add("telerik.common.css")
.Add("~/Content/Site.css")
.Add("~/Content/custom.css")
.Add("~/Content/themes/humanity/jquery-ui-1.8.18.custom.css")
.Combined(true)
.Compress(true)))
</head>
<body>
<div class="page">
<header>
<div id="header-logo">
<img alt="X" src="../../Content/Images/logo100.png"/>
</div>
<div id="title">
<h1>title</h1>
</div>
#(Html.Telerik().Menu()
.Name("menu")
.Items(menu =>
{
menu.Add().Text("Home").Action("Index", "Home");
menu.Add().Text("Products")
.Items(item =>
{
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
});
menu.Add().Text("Events").Action("Index", "Events");
menu.Add().Text("About Us").Action("About", "Home");
menu.Add().Text("Admin").Action("Index", "Admin");
})
.HtmlAttributes(new { style = "text-align:left;" }))
</header>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
#(Html.Telerik().ScriptRegistrar()
.Scripts(script=>script.Add("~/Scripts/custom.js"))
.Globalization(true)
.DefaultGroup(group => group.Combined(true)
.Compress(true)))
</body>
</html>
This is the base page view : Index.cshtml
#{
ViewBag.Title = "Admin";
}
<h2>
Admin Index</h2>
<div id="navAdminLeft">
#(Html.Telerik().TreeView()
.Name("AdminNavTree")
.Items(item =>
{
item.Add().Text("Products");
item.Add().Text("Categories");
item.Add().Text("Materials");
item.Add().Text("Finishes");
item.Add().Text("Packaging");
item.Add().Text("File Manager");
item.Add().Text("CategoryTree");
})
.ClientEvents(events => events.OnSelect("loadAdminContent"))
)
</div>
<div id="adminContent">
</div>
<script type="text/javascript">
function loadAdminContent(e) {
$.ajax({
type: "GET",
cache: false,
url: "Admin/" + e.item.innerText,
data: {},
success: function (data) {
$("#adminContent").html(data);
}
});
}
</script>
whenever the user selects a node on the #AdminNavTree the page fetches the content to be displayed and populates #adminContent. I am trying to build an edit page where there is a category tree listed in one div and when the user clicks on any of the category on that div, the details are ajax loaded into another div on the same page. Here is the partial view with the category tree that gets loaded into #adminContent: _CategoryTree.cshtml
#using xxx.Models.Navigation
#model IEnumerable<NavigationItem>
<div id="categoryTree">
#{Html.Telerik().TreeView()
.Name("ctree")
.BindTo(Model, mappings =>
mappings.For<NavigationItem>(binding => binding
.ItemDataBound((currentItem, navigationItem) =>
{
currentItem.Text = navigationItem.Text;
currentItem.Expanded = true;
})
.Children(child => child.Items)
))
.ClientEvents(events=>events.OnSelect("loadContent"))
.Render();
}
</div>
<div id="detail"></div>
<script type="text/javascript">
function loadCategoryDetail(e) {
$.ajax({
type: "POST",
url: "Admin/CategoryDetails",
data: { id: $("#ctree").data("tTreeView").getItemText(e.item) },
success: function (data) {
$("#detail").html(data);
}
});
}
</script>
the detail page that is ajax loaded does not contain any telerik controls so listing code for that is a non issue.
The PROBLEM : this will not render. As soon as it tries rendering #ctree treeview it starts throwing all kind of script errors, specifically it ignores loadCategories (says not found). So far I think what is happening is the ajax loaded partial page that contains the treeview is reloading the jquery lib destroying all old bindings and functions in the script. Is there a way to make this work, two treeviews on one page, one previously loaded, one in a ajax loaded partial view, both binding to separate data?
I've had good success with jsTree... doesn't help with your telerik question, but might be worth checking out.
http://www.jstree.com/