Angular Partials -- Calling From Controller Possible? - angularjs

I have an Controller that is grabbing data via a Factory. That Factory is attached to an API that is being served up by Laravel 5.
function HomeCtrl($scope, AccountService) {
$scope.accounts = [];
$scope.loadAccounts = function () {
AccountService.getData('account', 'active').then(function (data) {
$scope.accounts = data;
}
);
};
$scope.loadAccounts();
}
controllersModule.controller('HomeCtrl', HomeCtrl);
What I want this controller to do is call a partial view and feed the $scope.accounts into that partial view.
Here is what my overarching HTML file looks like that should load in the partial:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!--title('{{title}}')-->
<meta name="description" content="{{description}}">
<meta name="keywords" content="{{keywords}}">
<meta name="author" content="">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/handheld.css" media="screen and (min-width:0px) and (max-width:1024px)">
<link rel="stylesheet" href="css/tablet.css" media="screen and (min-width:768px) and (max-width:1024px)">
<link rel="stylesheet" href="css/mobile.css" media="screen and (max-width:767px)">
<base href="/">
</head>
<body>
<div id="wrapper">
<header id="header">
<div class="page clearfix">
<div class="top">
<ul>
<li>khaccsupport</li>
<li>khaccsupport</li>
<li>shane#khaccounts.net</li>
</ul>
</div><img src="../images/logo.png">
<section class="secondary-header">
<nav class="navigation">
<ul>
<li class="top-link">Buy WoW Accounts</li>
<li class="top-link">Sell WoW Accounts</li>
<li class="top-link">Reviews / Feedback</li>
<li class="top-link">FAQ</li>
</ul>
</nav>
</section>
</div>
</header>
<div class="fb-frame">
<iframe src="//www.facebook.com/plugins/like.php?href=https%3A%2F%2Fwww.facebook.com%2Fkhaccounts&amp;width=450&amp;height=35&amp;colorscheme=light&amp;layout=standard&amp;action=like&amp;show_faces=false&amp;send=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowtransparency="true"></iframe>
</div>
<div class="content">
<div class="page">
<div ui-view></div>
</div>
</div>
<div class="footer-wrapper index-page">
<footer id="footer">
<div class="page">
<div class="footer-content clearfix">
<div class="links-wrapper clearfix">
<section class="footer-links nav">
<h4>Navigation</h4>
<ul>
<li>Buy High End Elite Premium WoW Accounts<br>Sell High End Elite Premium WoW Accounts<br>High End Elite Premium WoW Accounts For Sale<br>KHAccounts.net Customer Reviews & Feedback<br>KHAccounts.net Buy & Sell WoW Accounts FAQ</li>
</ul>
<ul>
<li></li>
<div class="secondary-footer"><img src="../images/footer-logo.png"><span class="copyright">©2015 Knucklehead Accounts -- All Rights Reserved.</span></div>
</ul>
</section>
<section class="footer-links reference">
<h4>Referral Links</h4>
<ul>
<li>Anonymous WoW Armory Profiles<br>Trade WoW Accounts<br>MMO Game Account Trading<br>WoW Trading Forum</li>
</ul>
<ul>
<li>RBG Rating Boost<br>Arena Rating Boost<br>TwinkInfo.com<br>TwinkInfo.com Forums<br>Twinking Guides</li>
</ul>
</section>
</div>
</div>
</div>
</footer>
</div>
</div>
<script src="js/main.js"></script>
</body>
</html>
Also, I don't want to put a controller name on the div because I trying to reuse this wrapper for every page. The only thing that should change is the content in the ui-view when the user navigates to a new page or what not.
I don't know if all of this is possible, but I thought I would give it a shot.
Please let me know if you have any questions as I am sure that I didn't explain all of this correctly...

You need to use the ng-include directive if you plan to include partials. Check out this Plunker for reference.
<div ng-include="'HomePartial.html'"></div>
Will contain your home HTML markup. Inside this partial you will need to put the controller HomeCtrl.
<div ng-controller="HomeCtrl">
<h1>Home Partial</h1>
</div>
This allows you to keep your outer HTML markup as generic as possible and divide and conquer using partials. You can change the ng-include at runtime as needed (or better yet, using routes).

You can use ng-route to handle the controller association with the views. You don't need to specify the controller in the route itself.
<div class="container">
<h1>ng-route</h1>
<ul class="nav nav-tabs">
<li><a href='#view1'>View 1</a></li>
<li><a href='#view2'>View 2</a></li>
</ul>
<div ng-view></div>
</div>
<script type=text/ng-template id=partial/view1.html>
<h3>View1</h3>
<div>{{data}}</div>
</script>
<script type=text/ng-template id=partial/view2.html>
<h3>View2</h3>
<div>{{data}}</div>
</script>
Javascript
angular.module('app', ['myModule', 'ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/view1', {templateUrl: 'partial/view1.html', controller: 'ctrl'})
.when('/view2', {templateUrl: 'partial/view2.html', controller: 'ctrl2'})
.otherwise({redirectTo: 'view1'})
});
angular.module('myModule', [])
.controller('ctrl', function ($scope) {
$scope.data = 'Some data for view1';
})
.controller('ctrl2', function ($scope) {
$scope.data = 'Some data for view2';
});
View the demo on jsFiddle http://jsfiddle.net/neridum/whLa8k6k/

Related

partials aren't loading angularjs

please tell me why it isn't loading partials.
I'm trying to do routing and inserting a partial templates into the layout HTML page when you click on a specific hyperlink such as Home, about or contact.
I checked in every line of code and I didn't find the source of problem for not loading partials. Routes are doing fine, it just isn't loading.
Here's my code:
index.html
<html ng-app="streamApp">
<head>
<meta charset="utf-8">
<!-- To ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>StreamTest App</title>
<!-- load bootstrap and fontawesome -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="styles/style.css"/>
</head>
<body ng-app="streamApp" ng-controller="MainController">
<div id="main">
<!-- including header -->
<div ng-include="'views/templates/header.html'"></div>
<!-- this is where content will be injected -->
<div id="container" style="margin-top: 50px;">
<ng-view></ng-view>
</div>
<!-- including footer -->
<div ng-include="'views/templates/footer.html'"></div>
</div>
</body>
<!-- Scripts -->
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<script type="text/javascript" src="node_modules/angular-route/angular-route.min.js"></script>
<script src="app.js"></script>
<!-- Scripts End -->
</html>
app.js
// create the module named streamapp and include ngRoute for routing needs
var streamApp = angular.module('streamApp',['ngRoute']);
//configure app's routes
streamApp.config(['$routeProvider',function ($routeProvider) {
$routeProvider
//route for the home page
.when('/home', {
templateURL : 'views/partials/home.html',
controller : 'MainController'
})
//route for the about page
.when('/about', {
templateURL : 'views/partials/about.html',
controller : 'aboutController'
})
//route for the contact page
.when('/contact', {
templateURL : 'views/partials/contact.html',
controller : 'contactController'
})
.otherwise({
redirectTo: '/home'
});
}]);
// create the controller and inject Angular's $scope
streamApp.controller("MainController", function ($scope) {
// create a message to display in our view
$scope.home="Welcome Home!";
});
streamApp.controller("aboutController", function ($scope) {
// create a message to display in our view
$scope.about="Wanna hear about us! Here you are :)";
});
streamApp.controller("contactController", function ($scope) {
// create a message to display in our view
$scope.contact="Don't be shy to contact us!";
});
header.html
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="row">
<div class="navbar-header">
<a class="navbar-brand" href="#home">StreamTEST</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-envelope"></i> Contact</li>
</ul>
</div>
</div>
</nav>
</header>
home.html
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ home }}</p>
</div>
about.html
<div class="jumbotron text-center">
<h1>About Page</h1>
<p>{{ about }}</p>
</div>
contact.html
<div class="jumbotron text-center">
<h1>Contact Page</h1>
<p>{{ contact }}</p>
</div>
I had changed the default hash-prefix from '!' to empty string '' in app.js cause I'm using angularjs 1.6
$locationProvider.hashPrefix('');
Remove ng-app from your body element. You already have it on the outer html element.
I use ui-router instead of ngRoute, but they are very similar. A couple of things.
You need to set Html5Mode, which means you need to inject $locationProvider into your config and then issue:
$locationProvider.html5Mode(true)
You should set the base href in the <head> section of your index.html with:
<base href="/" >
You might also want to try ng-href instead of href on your links.

Output doesn't come for REST API Angular

I am working on the tutorial to build an AngularJs app where I am fetching information of users. When I am running the app and the output doesn't display.
My index.html
<!DOCTYPE html>
<html data-ng-app="myContactApp" >
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="app.js"></script>
<script src="appConfig.service.js"></script>
<script src="appname.service.js"></script>
<script src="contact.controller.js"></script>
<script src="contactdata.service.js"></script>
<title>My Contact Application</title>
</head>
<body>
<main>
<div class='container' ng-controller="contactController as ctrl">
<div class='row'>
<ul class="list-group">
<li class="list-group-item" ng-repeat="con in ctrl.contactArr" data-ng-click="ctrl.selectUser($index)">
<span>{{con.name.first+ " "+con.name.last}}</span>
</li>
</ul>
</div>
<div class='row'>
<div class="media">
<div class="media-left">
<a href="#">
<img data-ng-src="{{ctrl.selectedUser.picture.medium}}">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">{{ctrl.selectedUser.name.first+ " "+ctrl.selectedUser.name.last}}</h4>
<div>
<p>
<h6>Location</h6>
</p>
<p>
{{ctrl.selectedUser.location.street+" "+ctrl.selectedUser.location.city+" "+ctrl.selectedUser.location.state+" "+ctrl.selectedUser.location.postcode}}
</div>
<div>
<p>
<h6>Phone</h6>
</p>
<p>{{ctrl.selectedUser.phone}}</p>
</div>
<div>
<p>
<h6>email</h6>
</p>
<p>
{{ctrl.selectedUser.email}}</p>
</div>
</div>
</div>
</div>
</main>
</body>
</html>
My app.js
var app=angular.module("myContactApp",[]);
My appconfig.service.js
(function(){
var app=angular.module("myContactApp");
app.service("AppDataServiceSVC",function(appNameSVC){
this.Name=appNameSVC;
this.author='Bhaskar';
this.buildDate=new Date().toDateString();
});
})();
My appname.service.js file :-
(function (){
var app=angular.module("myContactApp");
app.value("AppNameSVC","My New Contact List");
})();
My contact.controller.js file
(function(){
var app=angular.module("myContactApp");
app.controller("contactController",contactCtrl);
function contactCtrl(ContactDataSVC){
var self=this;
ContactDataSVC.getContacts().then(function(data){
self.contacts=data;
})
this.selectUser=function(index){
this.selectedUser = this.contactArr[index];
}
}
})();
My contactdata.service.js
(function(){
var app=angular.module("myContactApp");
app.service("ContactDataSVC",function($http){
var self=this;
self.getContacts=function(){
var response1=$http.get('http://localhost:3000/contacts');
var response2=response1.then(function(response){
return response.data;
});
return response2;
}
});
})();
I have created db.json which I am running on json-server and using it as REST API. It should display contact details but it doesn't display anything on the browser. I am unable to figure out where I have made the mistake.
In controller you use: self.contacts=data;
Change ng-repeat="con in ctrl.contactArr" to:
ng-repeat="con in ctrl.contacts"
also pass con to selectUser : data-ng-click="ctrl.selectUser(con)"
Demo plunker

AngularJS Route does not loading view

My project structure is looks like this:
I tried to make a single page application using this image. When index.html page will launch it will by default load registration.html in ng-view. But when index.html loads it does not load the registration.html as ng-view as expected.
And my files for index.html,main.css and mainAppRouter.js are below:
//mainAppRouter.js
(function () {
var myModule = angular.module('studentInfo', ['ngRoute']);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/registration', {
templateUrl : '../views/registration.html',
controller: 'regController'
})
.otherwise({
redirectTo: '/registration'
});
console.log("checking");
});
myModule.controller('regController', function ($scope) {
$scope.message = 'This is Add new order screen';
console.log("checking");
});
});
/*man.css*/
.studentInfo{
margin-top: 100px;
}
.navbar{
padding: 1em;
}
.navbar-brand {
padding:0;
}
<!--index.html-->
<!DOCTYPE html>
<html data-ng-app="studentInfo">
<head>
<script src="lib/js/angular.min.js"></script>
<script src="lib/js/jquery-3.0.0.min.js"></script>
<script src="lib/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/js/angular-route.js"></script>
<script src="app/route/mainAppRouter.js"></script>
<link rel="stylesheet" href="lib/css/bootstrap.css" />
<link rel="stylesheet" href="lib/css/bootstrap-theme.css" />
<link rel="stylesheet" href="app/css/main.css" />
<title>A demo Angular JS app</title>
</head>
<body>
<div class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#"> <span><img src="app/images/people.png"/></span> Student Info </a>
</div>
<ul class="nav nav-pills navbar-right" data-ng-controller="NavbarController">
<li role="presentation">Registration</li>
<li role="presentation">Student Details</li>
</ul>
</div>
</div>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-ng-controller="regController">
<h1>Student Info</h1>
</div>
<div ng-view></div>
</div>
</body>
</html>
All my codes are in this github repo
What should i do to correct my problem?
I think the problem is because you have not specified any controller for your ng-view and also you have to set your base URL correctly.
$routeProvider
.when('/registration', {
templateUrl :'http://localhost/StudentInfo/app/views/registration.html',
controller: 'regController'
})
And remove the controller tag from HTML.Your controller tag was outside the scope of ng-view.
<div class="container">
<div class="col-md-4 col-md-offset-4" >
<h1>Student Info</h1>
</div>
<div ng-view></div>
</div>
And there is a syntax error in your controller as well
myModule.controller('regController', function ($scope){
$scope.message = 'This is Add new order screen';
})
UPDATED ANSWER: Another reason why this does not work is that you are running your example off the file system (using the file:// protocol) and many browsers (Chrome, Opera) restricts XHR calls when using the file:// protocol. AngularJS templates are downloaded via XHR and this, combined with the usage of the file:// protocol results in the error you are getting.
For more details: Couldn't load template using templateUrl in Angularjs

Angular ng-repeat and Bootstrap column not working

I have a ng-repeat that is displaying a list of items. I want them to be a col width of 2
This is the index.html body
index.html
<!DOCTYPE html>
<html ng-app="games">
<head>
<title>Games</title>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
<link rel="stylesheet" type="text/css" href="/static/css/fontello.css">
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<meta name=viewport content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript" src="/static/app/app.js"></script>
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body ng-controller="gamesCtrl">
<a ui-sref="games">Games</a>
<div class="container">
<div class="row">
<div ui-view></div>
</div>
</div>
</body>
</html>
And here is the HTML I am pulling for the ui-view
list.html
<div ng-repeat="game in games">
<div ng-class="col-xs-2">
{{ game.title }}
<img src="{{game.thumbnailUrl100}}"/>
</div>
</div>
What's happening though is its just stacking everything on top of each another and not putting it next to each other.
Here is the inspect element code
<div class="row">
<!-- uiView: -->
<div ui-view="" class="ng-scope">
<!-- ngRepeat: game in games -->
<div ng-repeat="game in games" class="ng-scope">
<div class="ng-binding">Cut The Rope</div>
<img src="https://az680633.vo.msecnd.net/thumbnail/40071/100/40071.png">
</div>
<!-- end ngRepeat: game in games -->
<div ng-repeat="game in games" class="ng-scope">
<div class="ng-binding">Cut The Rope: Time Travel</div>
<img src="https://az680633.vo.msecnd.net/thumbnail/40072/100/40072.png">
</div>
</div>
Just incase something else is wrong here is the js
angular.module('games', ['ui.router', 'ui.bootstrap'])
.config(function($urlRouterProvider, $locationProvider, $stateProvider) {
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/");
//take out #
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
// Now set up the states
$stateProvider
.state('games', {
url: "/",
templateUrl: "/static/app/list.html",
controller: 'gamesCtrl'
})
})
.controller('gamesCtrl', ['$scope', '$state', 'gamesFactory',
function($scope, $state, gamesFactory) {
$scope.$state = $state;
$scope.games = null;
function init() {
gamesFactory.getGames().success(function(games) {
$scope.games = games.data;
console.log($scope.games.data)
});
}
init();
}
])
.factory('gamesFactory', function($http) {
var factory = {};
factory.getGames = function() {
return $http.get('/games.json');
};
return factory;
});
ng-class is expecting an Angular expression. In this case, you are giving it the actual CSS class name. Angular tries to evaluate that as an expression, which results in undefined (or null or the empty string).
Since you don't need to do anything but apply the class name here, just use the regular class attribute instead of ng-class:
<div ng-repeat="game in games">
<div class="col-xs-2">
{{ game.title }}
<img src="{{game.thumbnailUrl100}}"/>
</div>
</div>
ng-class expects an expression. Change your markup like this:
<div ng-repeat="game in games">
<div ng-class="'col-xs-2'">
{{ game.title }}
<img src="{{game.thumbnailUrl100}}"/>
</div>
</div>
https://docs.angularjs.org/api/ng/directive/ngClass
The problem is that you're repeating the div around the columns, not the columns themselves. Try this:
<div class="col-xs-2" ng-repeat="game in games">
{{ game.title }}
<img src="{{game.thumbnailUrl100}}"/>
</div>
Try using ng-src on your image. At the time the page is first rendered, the image size probably can't be determined.
Edit, so the complete html should be:
<div ng-repeat="game in games">
<div class="col-xs-2">
{{ game.title }}
<img src= "" ng-src="{{game.thumbnailUrl100}}"/>
</div>
As others have pointed out, you shouldn't be using ng-class here.

why angular js routing does not work?

I have a menu in _Adminlayout.cshtml and i define my Route in it , this is all i did in:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/Styles/ThirdParties/Glazzed/Main.css" rel="stylesheet" />
<link href="~/Content/Styles/GlazzedOverride.css" rel="stylesheet" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/Scripts/ThirdParties/Glazzed/Main.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/Scripts/ThirdParties/Angular.js"></script>
<script src="~/Scripts/Scripts/ThirdParties/AngularRoute.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
#DefineApp()
</head>
<body>
<div>
<div class="container">
<div class="col col-md-9 pull-left">
#RenderBody()
#*<ng-view></ng-view>*#
<div ng-view></div>
</div>
<div class="col col-md-2 bg1">
<ul class="main-nav" ng-controller="menuController">
<li ng-repeat="menuItem in menuItems" class="{{ menuItem.submenuItems && menuItem.submenuItems.length > 0 ? 'main-nav--collapsible' : '' }}">
<a class="main-nav__link" ng-href="{{ menuItem.url || 'javascript:void(0);' }}">
<span class="main-nav__icon"><i class="{{ menuItem.icon }}"></i></span>
{{ menuItem.title }}
</a>
<ul ng-if="menuItem.submenuItems && menuItem.submenuItems.length > 0" class="main-nav__submenu">
<li ng-repeat="submenuItem in menuItem.submenuItems"><span>{{ submenuItem.title }}</span></li>
</ul>
</li>
</ul>
</div>
</div>
and this is the script :
<script>
App.config(['$routeProvider', function ($routeProvider) {
debugger;
$routeProvider
.when('/Admin/GetProducts', {
templateUrl: '#Url.Action("GetProducts","Product")'
})
.otherwise({
redirectTo: '/'
});
}]);
App.controller("menuController", function ($scope) {
debugger;
$scope.menuItems = [
{
title: 'ProductList',
icon: 'pe-7f-check',
url: '#/Admin/GetProducts'
}
]});
</script>
</div>
#helper DefineApp()
{
<script>
var App = angular.module("app", ['ngRoute']);
</script>
}
but my route does not work, what is the problem?
You're mixing Angular routing which was designed for SPA's and you also have MVC routing which isn't for SPA's. You have both technologies essentially fighting each other.
If you want to use Angular routing or Angular is general, I would recommend that you stop having your ASP.NET MVC controllers from returning any Views except for maybe "Index.cshtml"

Resources