AngularJS orderby / controller behavior: controller executed on orderby - angularjs

I took a sample AngularJS app and began to change it to suit my needs. Now clicking to change the orderby causes the entire controller to be reloaded. Well that's where I'm initializing the default orderby. So what I get when I click a new orderby is a flash of the proper orderby then a quick return to the default. An alert showed me the controller is getting executed but I don't know why or how to fix it.
Plunker here
index.html
<!DOCTYPE html>
<html data-ng-app="promptsApp">
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" />
</head>
<body>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="app.js"></script>
<script src="controllers.js"></script>
<script src="promptsService.js"></script>
</body>
</html>
app.js
var app = angular.module('promptsApp', []);
app.config(function ($routeProvider) {
$routeProvider
.when('/prompts',
{
controller: 'PromptsController',
templateUrl: 'partial.html'
})
.otherwise({ redirectTo: '/prompts' });
});
controllers.js
app.controller('PromptsController', function ($scope, promptsService)
{
init();
function init()
{
$scope.prompts = promptsService.getPrompts();
$scope.orderby='TRANSFEREE';
$scope.reverse = false;
//alert('Hi');
}
$scope.setOrder = function (orderby) {
if (orderby === $scope.orderby)
{
$scope.reverse = !$scope.reverse;
}
$scope.orderby = orderby;
};
});
promptsService.js
app.service('promptsService', function ()
{
this.getPrompts = function (user)
{
var prompts = [
{
id: 1, NOTE: 'Call client about something', CALLBACK_DATE: '12-01-2013', TRANSFEREE: 'Tom Tuttle', REG_NUM: '123456'
},
{
id: 2, NOTE: 'Notify client of delay', CALLBACK_DATE: '12-10-2013', TRANSFEREE: 'Eddie Munster', REG_NUM: '101314'
},
{
id: 3, NOTE: 'Complete paperwork', CALLBACK_DATE: '12-12-2013', TRANSFEREE: 'Mary Tyler Moore', REG_NUM: '998877'
}
];
return prompts;
};
});
partial.html
<div class="prompts">
<div class="container">
<header>
<h3>Prompts</h3>
<ul class="nav nav-pills">
<li ng-class="{'active': orderby=='CALLBACK_DATE'}">Date</li>
<li ng-class="{'active': orderby=='TRANSFEREE'}">Transferee</li>
<li> (Currently: {{orderby}})</li>
</ul>
</header>
<div>
<div class="row cardContainer">
<div class="span3 card" data-ng-repeat="prompt in prompts | orderBy:orderby:reverse">
<div class="cardHeader">{{prompt.TRANSFEREE}}</div>
<div class="cardBody">{{prompt.NOTE}}
<br># {{prompt.REG_NUM}} {{prompt.CALLBACK_DATE}}
</div>
</div>
</div>
</div>
<br />
{{prompts.length}} prompts
</div>
</div>
See Plunker here

<li ng-class="{'active': orderby=='CALLBACK_DATE'}">
<a href="" ng-click="setOrder('CALLBACK_DATE')">\
CallBack Date
</a>
</li>
<li ng-class="{'active': orderby=='TRANSFEREE'}">
<a href="" ng-click="setOrder('TRANSFEREE')">
Transferee
</a>
</li>
<li>> Currently: {{orderby}}</li>
Remove the href="#" and replace it with href="" to get the desired result.
Having href="#" causes the route to change (and become the same as before) but triggers the initialization of the controller once more.

Related

Angularjs routing issue controller not triggered after click the link ?

I have implemented the routing in our website i have properly link all the href with controller but i don't understand why controller is not fire check my fiddle code and tell what's the wrong in my code?
var app = angular.module("angularDemoApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when('/Family', {
templateURL : 'Family.html',
controller : 'familyController'
}).when('/Friends',{
templateURL : 'Friends.html',
controller : 'friendsController'
}).when('/Photo', {
templateURL : 'Photo.html',
controller : 'photoController'
})
})
app.controller('familyController', function($scope) {
$scope.msg = "hiii homeee";
});
app.controller('friendsController', function($scope) {
alert('ssss');
$scope.friendsMsg = "hiii friendsMsg";
});
app.controller('photoController', function($scope) {
alert('ssss');
$scope.photoMsg = "hiii photoMsg";
})
<ul class="nav nav-pills nav-stacked">
<li>
Family
</li>
<li>
Friends
</li>
<li>
Photos
</li>
</ul>
If you are using angular version above 1.6 routes changed from #/state to #!/state
DEMO
var app = angular.module("angularDemoApp", ["ngRoute"])
app.config(function($routeProvider) {
$routeProvider.when('/Family', {
template: `<h1>{{msg}}</h1>`,
controller : 'familyController'
}).when('/Friends',{
template: `<h1>{{friendsMsg}}</h1>`,
controller : 'friendsController'
}).when('/Photo', {
template: `<h1>{{photoMsg}}</h1>`,
controller : 'photoController'
})
})
app.controller('familyController', function($scope) {
$scope.msg = "hiii homeee";
});
app.controller('friendsController', function($scope) {
alert('ssss');
$scope.friendsMsg = "hiii friendsMsg";
});
app.controller('photoController', function($scope) {
alert('ssss');
$scope.photoMsg = "hiii photoMsg";
})
<!DOCTYPE html>
<html ng-app="angularDemoApp">
<head>
<meta charset="utf-8" />
<title>AngularJS User Registration and Login Example </title>
</head>
<body>
<ul class="nav nav-pills nav-stacked">
<li>
Family
</li>
<li>
Friends
</li>
<li>
Photos
</li>
</ul>
<div class="mainContainer" ng-view></div>
<script src="//unpkg.com/angular#1.6/angular.js"></script>
<script src="//unpkg.com/angular-route#1.6/angular-route.js"></script>
</body>
</html>

Passing Data between state Providers in angular

Im looking to pass data between 2 controllers in Angular, Below is code i started
There are 2 views one with input field and other with a link.
when i click on link in the second view i should be able to set a state and state data should be populated in input field in first field.
I tried several approaches but im missing something.
Can someone help me here
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider','$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <input type="text" ng-model={{input-text}}>' ,
data:""
},
viewBookv = {
name: 'viewBookv',
url: '/viewBook',
template: '<h2>View A book</h2><span class="glyphicon glyphicon-edit">Edit</span> ' ,
};
$stateProvider.state(addBook, "controller: editUserCtrl");
$stateProvider.state(viewBookv, "controller: editUserCtrl");
}])
myApp.controller('editUserCtrl', function($scope, $stateParams) {
$scope.paramOne = $stateParams.data;
$scope.edit = function () {
event.preventDefault();
$state.go("addBook");
}
})
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBookv");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
Typically in angular the way to share state between controllers is using a service. So the way it's usually set up is to setup a service then import that service into the relevant controllers, and that data gets shared between them. I've modified your example above to follow this pattern(I'm not quite sure what you were trying to do)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <button ng-click="updateBook()">Update</button> <input type="text" ng-model="inputText">' ,
controller: "addBookCtrl",
data:""
},
viewBookv = {
name: 'viewBooks',
url: '/viewBook',
template: '<h2>View A book</h2><div ng-repeat="book in bookList">{{book}}</div>',
controller: "viewBookCtrl",
};
$stateProvider.state('addBook', addBook);
$stateProvider.state('viewBooks', viewBookv);
}])
myApp.controller('addBookCtrl', function($scope, bookService) {
$scope.updateBook = function(){
console.log( $scope.inputText)
bookService.books.push($scope.inputText);
}
})
myApp.controller('viewBookCtrl', function($scope, bookService) {
$scope.bookList = bookService.books
})
myApp.factory('bookService', function() {
var bookService = {};
bookService.books = [];
return bookService;
});
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBooks");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
What this example does, is in the text box for add book, you type in the name (then click update), this appends it to an array so every time you do it you'll get a new element on that array. From there head over to the view books page, and you'll see all the different things you typed in.

AngularJS How to add template inside of a HTML div

I have a index page which is divided to 4 divs. What i m trying to do is when the user clicks on a link in the navigation bar, the template is loaded in the div. For example, if the user clicks on the ex1 then the first div in the html supposed to show the content of the template. Any ideas how can i do it ?
<body ng-controller="MainController">
<nav class="navbar navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('#ex1')}">Ex1</li>
<li ng-class="{ active: isActive('#ex2')}">Ex2</li>
<li ng-class="{ active: isActive('#ex3')}">Ex3</li>
<li ng-class="{ active: isActive('#ex4')}">Ex4</li>
</ul>
</div>
</div>
</nav>
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
<div id="div4">
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade
your browser</a> to improve your experience.</p>
<![endif]-->
<div ng-view>
</div>
<footer ng-include="'partials/footer.html'" style="position: fixed; bottom: 0"></footer>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="controllers/Ex1Ctrl.js"></script>
<script src="controllers/Ex2Ctrl.js"></script>
<script src="controllers/Ex3Ctrl.js"></script>
<script src="controllers/Ex4Ctrl.js"></script>
<script src="services/ex1Service.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
</body>
app.js
use strict';
// Declare app level module which depends on views, and components
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/ex1', {
templateUrl: 'partials/ex1.html',
controller: 'Ex1Ctrl'
});
$routeProvider.when('/ex2', {
templateUrl: 'partials/ex2.html',
controller: 'Ex2Ctrl'
});
$routeProvider.when('/ex3', {
templateUrl: 'partials/ex3.html',
controller: 'Ex3Ctrl'
});
$routeProvider.when('/ex4', {
templateUrl: 'partials/ex4.html',
controller: 'Ex4Ctrl'
});
$routeProvider.otherwise({
redirectTo : '/'
});
}]);
app.controller('MainController', ['$scope', function ($scope) {
}]);
Ex1 template
<div id = "ex1">
<div >click to see your lucky number<button class="btn btn-default" style="margin-left: 5px" ng-click="findRandom()">Click</button></div>
<div>{{random}}</div>
</div>
Ext1 controller
angular
.module('app')
.controller('Ex1Ctrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.findRandom = function(){
$scope.random=Calculator.number();
}
}]);
Currently your template will populate the <ng-view> view tag when you navigate to '/ext1'. If I understand you correctly you want the template contents to appear inside div1 when '/ext1' is navigated to...
Off the top of my head below code would achieve that by listening for the $routeUpdate event...
app.directive('luckyNumberGenerator', function(){
return {
templateUrl: '/path/to/the/template.html',
controller: function($scope, $location){
$scope.$on('$routeUpdate', function(){
$scope.showLuckyNumberGenerator = $location.path() === '/ext1';
});
}
}
});
... add an ng-show to your template...
<div id = "ex1" ng-show="showLuckyNumberGenerator">
<div >click to see your lucky number<button class="btn btn-default" style="margin-left: 5px" ng-click="findRandom()">Click</button></div>
<div>{{random}}</div>
</div>
.. and put the directive into the div.
<div id="div1">
<lucky-number-generator></lucky-number-generator>
</div>
It's worth noting that when you want to do any complex routing of panels and nested partial views you should look into using ui.router...

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"

Loading image at the time of onclick event using angularjs is not working

I want to add data at the time of onclick event. Need to load image at the time of onclick event, after a small time interval add data. But my image is continuously loading. Any body give any suggestion.
My code is:
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
<script language="javascript">
function ContactController($scope) {
$scope.contacts = [];
$scope.items = [ ];
$scope.add = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.items[0].lateLoader = ' xxxx ';
});
}, 1000);
$scope.count=$scope.count+1;
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
</script>
</head>
<body >
<div ng-app="" ng-controller="ContactController">
<p>{{items.lateLoader}}
<i ng-hide="items.lateLoader"><img src="Filling broken ring.gif"></i>
</p>
{{ contacts.length }}
Content:<input type="text" ng-model="newcontact" />
<button ng-click="add()">Add</button>
<ul style="list-style-type: none;">
<li ng-repeat="contact in contacts"> <input name="" type="checkbox" value="">{{ contact }}</li>
</ul>
</div>
</body>
</html>
In your example I found a lot of mistakes. The HTML tag is not defined at the top, wrong use of angularJs and Angular module is not created properly etc.
I fixed all the mistakes. I hope it can help you.
Plunkr link: http://plnkr.co/edit/no8WOHdEc9wc3dHzzITv?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script >
angular.module("app",[]).controller('ContactController',['$scope',
function($scope) {
$scope.contacts = [];
$scope.items = [];
$scope.add = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.items.lateLoader = 'xxxx ';
});
}, 1000);
//$scope.count=$scope.count+1;
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
]);
</script>
</head>
<body >
<div ng-controller="ContactController">
<p>{{items.lateLoader}}
<i ng-hide="items.lateLoader">
<img src="https://encrypted-tbn1.gstatic.com
/images?q=tbn:ANd9GcQTaHe0F0J39SXbiRF43pz2wtyfD6kypCMrLxhWPkq9EACNgwO0iaMbJFM">
</i>
</p>
{{contacts.length}}
Content:<input type="text" ng-model="newcontact" />
<button ng-click="add()">Add</button>
<ul style="list-style-type: none;">
<li ng-repeat="contact in contacts">
<input name="" type="checkbox" value="">{{ contact }}
</li>
</ul>
</div>
</body>
</html>
And for more detail of angularJs please visit these links:(https://angularjs.org/)
(http://www.w3schools.com/angular/default.asp)

Resources