AngularJS controller, template and routing issue - angularjs

I am having a few issues getting my head around why this is not working:
template
<div>
<ul>
<li ng-repeat="x in get">
{{ x.name }}
</li>
</ul>
</div>
controller
angular.module('app')
.controller('SubstancesCtrl', function ($scope) {
$scope.get = [{name: "LOL"}];
});
routes
angular.module('app')
.config(function ($routeProvider) {
$routeProvider
.when('/', { controller: 'PostsCtrl', templateUrl: '/templates/posts.html' })
.when('/register', { controller: 'RegisterCtrl', templateUrl: '/templates/register.html' })
.when('/login', { controller: 'LoginCtrl', templateUrl: '/templates/login.html' })
.when('/substances', { controller: 'SubstancesCtrl', templateUrl: '/templates/substances.html'})
});
index.html
<!DOCTYPE html>
<html ng-app='app'>
<head>
<link rel='stylesheet' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>
<link rel='stylesheet' href='/app.css'>
</head>
<body ng-controller='ApplicationCtrl'>
<nav class='navbar navbar-default'>
<div class='container'>
<ul class='nav navbar-nav'>
<li><a href='/#/'>Posts</a></li>
<li><a href='/#/register'>Register</a></li>
<li><a href='/#/login'>Login</a></li>
<li>Substances</li>
</ul>
<p ng-if='currentUser' class='navbar-text navbar-right'>
Signed in as {{currentUser.username}}
</p>
</div>
</nav>
<div class='container' ng-view></div>
<script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular-route.js'></script>
<script src='/app.js'></script>
</body>
</html>
I can see that the template is being replaced by the ng-view directive however the get variable is not being treated in the manner i thought it would: i thought i would get one list item node with the value of LOL

You angular module has not been created, You should declare your module in app.js. As you are using angular routing you need to include its module in your app module.
angular.module('app',['ngRoute'])
Also you need to update your Angular to stable versions 1.4.4 is stable one, because you are using 1.3.0-rc.4 in which rc stands for release candidate which is pre-release version, which may have bug in most of the cases. Thats why I told you to go for stable version of AngularJS. You could also use close stable version which is 1.3.14
Additionally your template has <li ng-repeat="x in get()"> but get function is not defined in the scope, resultant would be nothing would be render on the UI.
angular.module('app')
.controller('SubstancesCtrl', function ($scope) {
$scope.lol = "LOL";
$scope.get = function(){
//write a code here which will return list
//so that ng-repeat will loop through the list
//& will show that data on HTML
//something like below
return {"name": "LOL"}; //in real case there must be something different object to return.
}
});

Alexis King was quite correct in that there were 3 very embarrassing issues with the code, it should have looked like this ( -_- )
template
<div>
<ul>
<li ng-repeat="x in get">
{{ x.name }}
</li>
</ul>
</div>
controller
angular.module('app')
.controller('SubstancesCtrl', function ($scope) {
$scope.get = [{name: "LOL"}];
});
routes were exactly the same.
The biggest issue however was in my gulp script which failed to pick up changes in these new files, I have rewrote the build script to ensure all files from the directories containing these files now are watched and all changes are reflected in the browser.
My excuse: need more coffee.

Related

Routes: controller doesn't get called

I have three files:
index.html
players.html
app.js
index.html: pretty simple.
<body>
<main ng-view></main>
</body>
players.html: which should display a list of players.
<section>
<ul>
<li ng-repeat="player in players">
<h4>{{player}}</h4>
</li>
</ul>
</section>
app.js: which contains a route to /players and controller that has a list of players to be displayed on the view.
// Module
const myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', $routeProvider => {
$routeProvider
.when('/players', {
controller: 'playersController',
templateUrl: 'views/players.html'
})
}]);
// Controller
myApp.controller('playersController', ['$scope', $scope => {
$scope.players = ['Kaka', 'Maldini', 'Nesta'];
}]);
When I route to '/players', the controller doesn't get called and nothing displays, however when I use ng-include instead and add the controller as an attribute, it works fine.

Angularjs ngRoute not routing as it should

first of all sorry if I write with bad grammar/expressions, my english is not the best.
Well, I'm trying to show a product via ID, for this I'm sending this ID from a list of products with this url: localhost/products/product/:ID and I'm receiving GET http://localhost/products/product/101 404 (Not Found)(the 101 is an example).
If I go to http://localhost/products/product.html it is changed for http://localhost but is not redirected, just change the url in the address bar
Here is my code
var app = angular.module('AppMarketApp', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled:true,
requireBase: false});
$routeProvider
.when("/products/product/:codProd", {
templateUrl: '../js/product/appInfo.html',
controller: 'Controller'
})
.otherwise({redirectTo:'/'});;
});
app.controller("Controller",['$scope','$http', '$routeParams', function($scope,$http, $routeParams){
$scope.row = {};
var codProd= $routeParams.codProd;
//some extra code here.
directive
app.directive('appInfo', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: '../js/product/appInfo.html'
};
});
and html
<body ng-app="AppMarketApp" ng-controller="Controller">
<div class="page" style="">
<div class="content-showproduct">
<div class="product" ng-view>
<app-info info="arts"></app-info>
</div>
</div>
</div>
<script src="../js/product/Controller.js"></script>
<script src="../js/product/appInfo.js"></script>
</body>
Any ideas? if you guys need some extra info let me know.
In addition, I think that I have some bad code in the HTML file, more specifically here
<div class="product" ng-view>
<app-info info="arts"></app-info>
</div>
I dont know if it will work well after routing. Without ng-view in others files works well. But is not important right now.

Angular.JS on Firefox Junk after document element error

When I test my index.html on Firefox with console.log it reads a strange error that says. I can't make the oage run on Google Chrome or IE.
junk after document element
This error is caused by the main.html page
<h1>This is my main</h1>
<h3>Scope value: {{ name }} </h3>
I'm just learning angular.js, in fact my code is exactly like this tutorial I was following, but I can't figure out why is not working. Can anyone point me in the right direction and tell me:
Why am I getting the console log error: Junk after document error, and
why can't I make ngview and templateURL work on my site?
Thanks!
My Plnkr Example
App.JS:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateURL: 'pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
$scope.name = 'Main';
}]);
myApp.controller('secondController', ['$scope', '$log', function($scope, $log) {
$scope.name = 'Second';
}]);
Index.HTML
<header> <nav class="navbar navbar-default"> <div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i>Home</li>
<li><i></i>Second</li>
</ul> </div> </nav> </header>
<div class="container">
<div ng-view></div>
</div>
Main.HTML
<h1>This is my main</h1>
<h3>Scope value: {{ name }} </h3>
Second.HTML
<h1>This is my second</h1>
<h3>Scope value (on second page): {{ name }} </h3>
the code does not run on IE or Chrome cause they don't have a built in localhost feature. Firefox does.
Regarding the Error, I am not 100% sure but I believe that it has to do with Angular HTML format support in the browser itself. I am taking the same course now and facing the same issue. But the app is working fine except for those errors in Firefox.
Chrome: no errors.
MS Edge: no errors.
IE: no errors
===========================
update
Try using Brackets text editor, and use the Live Preview feature.
Open the Index.HTML page in Brackets and hit the button on the top right corner.

Typescript - change DOM element inner HTML?

I've been searching around this afternoon trying to figure out how to use Typescript to change the html of a span element in my breadcrumb trail, OR get an angular statement to evaluate/compile in a jQuery selector. The closest I've found is to use $compile, but I'm not sure if this will work since I don't have the data until after my resolve completes? If it will, I'll need a hand understanding where to inject $compile into the app.
index.module.ts
angular.module('pccrm', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource',
'ui.router', 'ui.bootstrap', 'feature-flags', 'trNgGrid', 'pascalprecht.translate', 'toastr', 'cgBusy',
'fixtable', 'angularUtils.directives.uiBreadcrumbs', 'LocalStorageModule'])
...
index.route.ts
...
.state(Constants.SEARCH_CONTACTS_CONTACTPROFILE, {
url: '/orgs/:externalOrgId/contacts/:profileId',
data: {
displayName: 'Contact Profile'
},
views: {
'': {
templateUrl: 'app/contacts/contact-profile.tmpl.html',
controller: 'ContactsProfileController',
controllerAs: 'cpc',
resolve: {
contactProfile: function (contactProfileService: IContactProfileService, $stateParams: any) {
return contactProfileService.getContactProfile(<string>$stateParams.externalOrgId, <string>$stateParams.profileId)
.then(function (contactModel: IContact) {
return contactModel;
});
}
}
}
}
})
...
contact-profile.tmpl.html
...
<div class="info-group">
<div class="profileImage default">
</div>
<h4 class="contact-name">{{ cpc.contactProfile.fullName() }}</h4>
{{ cpc.contactProfile.title }}<br/>
<a ui-sref="search.organizations.orgProfile({externalOrgId: cpc.contactProfile.externalOrganizationId })" ng-if="cpc.contactProfile.externalOrganizationId">
{{ cpc.contactProfile.externalOrganizationName }}
</a>
</div>
...
Is something like...
<script type="text/javascript">
$('.breadcrumb li.active span').html(
$compile("{{ cpc.contactProfile.fullName() }}")(scope));
</script>
on the end of the template html the best way to do this? Or can my profile service edit the DOM somehow once it retrieves the contact info?
NOTE We're using angular-util-sui-breadcrumbs to generate the BCT...which currently doesnt support interpolating the resolve into the BCT with the way we have our nested named views. This is why I need to be able to modify the BCT dom after the fact.
Or can my profile service edit the DOM somehow once it retrieves the contact info
Yes. Export the stuff on the scope and use that {{somethingOnScope.contactProfile.fullName()}} in the UI.
More on scope : https://docs.angularjs.org/guide/scope
Update
You may have misread my question
No. I am saying that don't do:
$('.breadcrumb li.active span').html(
$compile("{{ cpc.contactProfile.fullName() }}")(scope));
Instead your html should look like:
<ul class="breadcrumb">
<li class="active">
<span>{{somethingOnScope.contactProfile.fullName()}}</span>
</li>
</ul>
And then you don't need jquery 🌹

One Angular page with many url:s

I have a simple Angular app (for training purpose since I am a Angular-rookie :)) with a ul-list containing some books. If the user clicks on a book a detail view will appear below the list with some details about that book. I want that if the user clicks on the book the url should change to something like /#/[book-id]. The user should also of course be able to browse directly to this url where the details view for the specific book is visible. I have not figure out how to do this with routes. I paste my sample code below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body ng-app="libraryApp">
<div id="list" ng-controller="listCtrl">
<ul ng-repeat="book in data.list">
<li>{{ book.name }}</li>
</ul>
</div>
<div id="detailView" ng-controller="detailCtrl">
<div ng-if="data.currentBook" style="background-color: #EEE; padding: 10px 0;">
<h1>{{ data.currentBook.name }}</h1>
<div>Number of pages: {{ data.currentBook.pages }}</div>
</div>
</div>
</body>
</html>
<script>
angular.module("libraryApp", [])
.factory("dataFactory", function() {
return {
list: [
{ id: 1, name: "The Great Gatsy", pages: 423 },
{ id: 2, name: "1984", pages: 332 },
{ id: 3, name: "The Lord Of The Rings", pages: 632 }
],
currentBook: null
};
})
.controller("listCtrl", function($scope, dataFactory) {
$scope.data = dataFactory;
$scope.openDetailView = function(book) {
$scope.data.currentBook = book;
};
})
.controller("detailCtrl", function($scope, dataFactory) {
$scope.data = dataFactory;
});
</script>
you have to put this code in your code ...
angular.module("libraryApp", ['ngRought'])
.config(function ($routeProvider)
{
$routeProvider
.when("/bookname",
{
templateUrl: "path of the html file",
controller: "listCtrl"
})
.when("/date",
{
templateUrl: "path of the html file",
controller: "detailCtrl"
})
Kinda difficult to answer since there are so many ways to do this, but look into https://github.com/angular-ui/ui-router
You'll use your module's config block to set up the routing with $stateProvider, then specify the controllers and templates you'd like to use when a user changes the application's state. This means you'll probably need to move those divs for your different views to separate files (or something creative to get their content -- getting the element's html with jQuery or something would work).
I'm not going into many details because this is something that can be answered easily now that you know to use ui-router :)
It's called nested view. To use it you'd be better try ui-router: https://angular-ui.github.io/ui-router/sample/#/contacts/1/item/b

Resources