Angular JS - How can i animate on model change? - angularjs

i'm trying to do a nice fadeout+fadein transition when the currentVertical changes.
in knockout it was so simple but i can't figure it out here. please help.
the following code displays a UL list which is "bound" to a pricings array in the $scope.currentVertical when an LI element is clicked, the $scope.currentVertical is changed and the UL list updates accordingly. This works fine, but i would like the entire #container div to fade out and fadein when $scope.currentVertical is changed. Please help...
My html:
<body>
<h1>Pricing Poll</h1>
<div ng-controller="VerticalsController">
<div id="container">
<h2>{{currentVertical.title}}</h2>
<ul>
<li ng-repeat="pricing in currentVertical.pricings">
<a ng-click="currentVertical.selectPricing(pricing)">{{pricing.name}}</a>
</li>
</ul>
</div>
</div>
</body>
my javascript:
function VerticalsController($scope) {
$scope.verticals = [
{
title:'internet',
pricings: [
{
name: 'netvision',
monthly: 23
},
{
name: 'hot',
monthly: 33
},
{
name: '012',
monthly: 28
}
]
},
{
title:'cellular',
pricings: [
{
name: 'cellcom',
monthly: 20
},
{
name: 'pelephone',
monthly: 30
},
{
name: 'orange',
monthly: 25
}
]
},
{
title:'banks',
pricings: [
{
name: 'leumi',
monthly: 20
},
{
name: 'poalim',
monthly: 30
},
{
name: 'benleumi',
monthly: 25
}
]
}];
$scope.selected = [
];
$scope.currentIndex = 0;
$scope.currentVertical = $scope.verticals[0];
$scope.selectPricing = function(pricing) {
$scope.selected.push(pricing);
$scope.currentIndex++;
$scope.currentVertical = $scope.verticals[$scope.currentIndex];
};
/*$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};*/
}

You have to use custom or create directives to start advanced DOM manipulation like animations.
Here's a fiddle with the animation you requested, I use the visible variable on scope to trigger fading and the $timeout service to only change the selectedItem when fadeOut, it could be improved to pass a timeout and a callback as a directive option...
Fiddle: http://jsfiddle.net/g/Bs66R/1/
JS:
function VerticalsController($scope, $timeout) {
$scope.verticals = [{
title:'internet',
pricings: [{
name: 'netvision',
monthly: 23
},
{
name: 'hot',
monthly: 33
},
{
name: '012',
monthly: 28
}]
},
{
title:'cellular',
pricings: [{
name: 'cellcom',
monthly: 20
},
{
name: 'pelephone',
monthly: 30
},
{
name: 'orange',
monthly: 25
}]
},
{
title:'banks',
pricings: [{
name: 'leumi',
monthly: 20
},
{
name: 'poalim',
monthly: 30
},
{
name: 'benleumi',
monthly: 25
}]
}];
$scope.selected = [
];
$scope.currentIndex = 0;
$scope.currentVertical = $scope.verticals[0];
$scope.selectPricing = function(pricing) {
$scope.selected.push(pricing);
$scope.currentIndex++;
$scope.visible = false;
$timeout(function(){
$scope.currentVertical = $scope.verticals[$scope.currentIndex];
$scope.visible = true;
}, 1000);
};
$scope.visible = true;
}
var fadeToggleDirective = function() {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.uiFadeToggle, function(val, oldVal) {
if(val === oldVal) return; // Skip inital call
// console.log('change');
element[val ? 'fadeIn' : 'fadeOut'](1000);
});
}
}
}
angular.module('app', []).controller('VerticalsController', VerticalsController).directive('uiFadeToggle', fadeToggleDirective);
angular.bootstrap(document.body, ['app']); angular.bootstrap(document.body, ['app']);
HTML:
<h1>Pricing Poll</h1>
<div ng-controller="VerticalsController">
<div id="container" ui-fade-toggle="visible">
<h2>{{currentVertical.title}}</h2>
<ul>
<li ng-repeat="pricing in currentVertical.pricings">
<a ng-click="selectPricing(pricing)">{{pricing.name}}</a>
</li>
</ul>
</div>
</div>

I recommend you use the new ngAnimate directive provided in the AngularJS Core.
Read more here

Related

ng-click does not call function in mdDialog

I am a little new to AngularJS but I cannot figure out why the ng-click here will not call th addingSt() function, I wonder if it has something to do with the fact that it is being called from a mdDialog. Thanks for your help.
Heres my html for the mdDialog:
<md-dialog aria-label="Send Email">
<md-dialog-content>
<h3>Issue Details</h3>
<h4>Description</h4>
<md-input-container>
<label>Add description:</label>
<textarea class="form-control input-lg" style="width: 500px; height:100px;"></textarea>
</md-input-container>
<h3>Sub-tasks:</h3>
<md-list-item ng-repeat=" subtask in subtasks">
<p>{{subtask.content}}</p>
<md-checkbox aria-label="blarg" class="md-secondary" style="padding-right:60px;" ng-click="removeSubTask(subtask,$index)"></md-checkbox>
<md-list-item ng-if="addingTask === true"> <input ng-if="addingTask===true" ng-model="task.content" aria-label="blarg" placeholder="Add Subtask Here"></input>
</md-dialog-content>
<md-dialog-actions>
<md-button ng-show="addingTask === false" ng-click="addingSt()" class="btn btn-primary">
Add Sub-Task
</md-button>
<md-button ng-show="addingTask === true" ng-click="addingSt()" class="btn btn-primary">
cancel
</md-button>
<md-button ng-show="addingTask === true" ng-click="addSubTask()" class="btn btn-primary">
Submit
</md-button>
<md-button ng-click="closeDialog()" class="btn btn-primary">
Close
</md-button>
Here's the controller for the parent of the above mdDialog, (the controller for the mdDialog is nested inside it and works fine for all functions accept the addingSt() function)
var app = angular.module('epr')
app.controller('adminMainCtr',[ '$scope','$mdDialog',function($scope, $mdDialog) {
$scope.issues = [
{ name: 'Blizzard', img: 'img/100-0.jpeg', WardMessage: true, index:0, subtasks:[{content:"Shovel Sister Pensioner's Driveway "},
{content:"Clear downed trees at the Bush's home "}]},
{ name: 'Tornado', img: 'img/100-1.jpeg', WardMessage: false, index:1, subtasks:[{content:"",index:0}] },
{ name: 'Peterson Family Car Crash', img: 'img/100-2.jpeg', WardMessage: false, index:2, subtasks:[{content:"",index:0}] },
{ name: 'Flood', img: 'img/100-2.jpeg', WardMessage: false, index:3, subtasks:[{content:"",index:0}] },
{ name: 'School Shooting', img: 'img/100-2.jpeg', WardMessage: false, index:4, subtasks:[{content:"",index:0}] }
];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
//parent: parentEl,
templateUrl:'views/issue.html',
locals: {
items: $scope.items,
issue: issue
},
controller: DialogController
});
function DialogController($scope, $mdDialog) {
$scope.subtasks = issue.subtasks;
$scope.addingTask = false;
$scope.task={content:""};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask,index){
$scope.subtasks.splice(index,1);
}
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
Any help that you can lend me would be very appreciated!!!
You messed with the HTML and angylar code.
Errors found:
1) angular module initialization.
var app = angular.module('MyApp', ['ngMaterial'])
2) You placed some function outside the DialogController
3) md-list-item HTML has no end tags.
Created working Plunkr here. https://plnkr.co/edit/Sl1WzLMCd8sW34Agj6g0?p=preview . Hope it will solve your problem.
(function() {
'use strict';
var app = angular.module('MyApp', ['ngMaterial'])
app.controller('adminMainCtr', ['$scope', '$mdDialog', function($scope, $mdDialog) {
$scope.issues = [{
name: 'Blizzard',
img: 'img/100-0.jpeg',
WardMessage: true,
index: 0,
subtasks: [{
content: "Shovel Sister Pensioner's Driveway "
}, {
content: "Clear downed trees at the Bush's home "
}]
}, {
name: 'Tornado',
img: 'img/100-1.jpeg',
WardMessage: false,
index: 1,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Peterson Family Car Crash',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 2,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Flood',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 3,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'School Shooting',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 4,
subtasks: [{
content: "",
index: 0
}]
}];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
templateUrl: 'mddialog.html',
locals: {
message: {
items: $scope.items,
issue: issue
}
},
controller: DialogController
});
}
function DialogController($scope, $mdDialog, message) {
console.log(message)
//$scope.subtasks = message.issue.subtasks;
$scope.addingTask = false;
$scope.task = {
content: ""
};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask, index) {
$scope.subtasks.splice(index, 1);
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if ($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if ($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
})();

Angularjs directive scope seems not binding to value

Please spare me if this is a beginner type of question. I'm playing Highcharts.js with Angular.js, but it's seems like directive scope is not binding to value. Below are my codes.
HTML - but it's working inside this expressions {{xaxis}} {{seriesdata}}
<div class="container" ng-controller='chartController'>
<div class="row">
<div class="col-md-6">
<line-chart xaxis='xaxis' seriesdata='seriesdata'></line-chart>
{{xaxis}}
{{seriesdata}}
</div>
<div class="col-md-6">
<bar-chart options='pieOptions'></bar-chart>
</div>
</div>
</div>
directive.js
(function() {
'use strict';
angular
.module('chart')
.directive('lineChart', lineChartDirective);
/* #ngInject */
function lineChartDirective() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
xaxis: '=xaxis',
seriesdata: '=seriesdata'
},
link: function(scope, element) {
Highcharts.chart(element[0], {
chart: {
type: 'spline',
zoomType: 'x'
},
plotOptions: {
line: {
dataLabels: {
enabled: true
}
}
},
title: {
text: 'Profit Ratio by Month'
},
xAxis: {
categories: scope.xaxis
},
yAxis: {
title: {
text: 'Profit %'
}
},
series: [
{
name: 'Total',
data: scope.seriesdata
}
]
});
}
}
}
})();
service.js
(function() {
'use strict';
angular
.module('chart')
.factory('chartData', chartDataFactory);
chartDataFactory.$inject = ['$http'];
/* #ngInject */
function chartDataFactory($http) {
function getData() {
return $http.get('../../data/sampleData.json').then(function(result) {
return result.data;
})
}
return {
getData: getData
}
}
})();
controller.js
(function() {
'use strict';
angular
.module('chart')
.controller('chartController', chartController);
chartController.$inject = ['$scope', 'chartData', 'lodash'];
/* #ngInject */
function chartController($scope, chartData, lodash) {
var vm = this;
chartData.getData().then(function(data) {
$scope.chartData = data;
$scope.xaxis = data.SEO[0]["SEO-MOD-001"]["SEO-END-001"];
$scope.seriesdata = data.SEO[0]["SEO-MOD-001"]["SEO-END-002"];
console.log($scope.xaxis);
console.log($scope.seriesdata);
});
$scope.pieOptions = {
chart: {
type: 'column'
},
title: {
text: 'Projects'
},
xAxis: {
categories: ['Noreil', 'Ken', 'Alfie', 'Francis']
},
yAxis: {
title: {
text: 'Completed Projects'
}
},
series: [
{
name: 'Quarter 1',
data: [23, 11, 34, 26]
},
{
name: 'Quarter 2',
data: [14, 20, 26, 30]
}
]
}
}
})();
When the directive link function gets executed, you don't have data yet. So try following in link function:
var unwatch = scope.$watch('[xaxis, seriesdata]', function (results) {
if (results[0] && results[1]) {
init();
unwatch();
}
}, true);
function init() {
// Highcharts.chart(element[0], { ...
}

How to bring dynamicaly scope in view

In my controller I have this code:
$scope.lists = [{
listName: 'list1'
}, {
listName: 'list2'
}];
angular.forEach($scope.lists, function(item) {
var listName = item.listName;
$scope[listName] = [{
Name: 'Stefan'
}, {
Name: 'Stefan'
}, {
Name: 'Stefan'
}, {
Name: 'Stefan'
}];
});
The Input from lists cames from a webservice, so the values (list1 and list2) can be different each time i reload the app. I can also more then 2 items in lists.
How can I show the value from $scope[listName] in an ng-repat section in my view?
Thanks for your Help.
Stefan.
You might try something like this:
(function() {
angular.module("myApp", []).controller("controller", ["$scope",
function($scope) {
$scope.lists = [{
listName: "list1"
}, {
listName: "list2"
}];
angular.forEach($scope.lists, function(item) {
var listName = item.listName;
$scope[listName] = [{
Name: "Stefan"
}, {
Name: "Stefan"
}, {
Name: "Stefan"
}, {
Name: "Stefan"
}];
$scope.results = $scope[listName];
});
}
]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="myApp">
<div data-ng-controller="controller">
<ul>
<li data-ng-repeat="item in results">{{item.Name}}</li>
</ul>
</div>
</div>

Unable to use variable in angularjs ng-include

i build a list using .factory and in every elemt have a arrtibute which store page which needed to be include when clicked on any list item
.
i am unable to use this attribute dynamiclly ..plzz help,,,,
i am using ionic framework
////////////// service.js ////////////////
angular.module('starter.services', [])
.factory('Ctopic', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [ { title: 'Arrays', id:11 ,desc: "'ctopic/Union.html'"},
{ title: 'Bit Field Declaration', id:12 },
{ title: 'C Pointers', id: 13 },
{ title: 'Conditional Statements', id: 14 },
{ title: 'File IO', id: 15 },
{ title: 'Function', id: 16 },
{ title: 'Input & Output', id: 17 },
{ title: 'Loops', id: 18 },
{ title: 'Preprocessor Operators', id: 19 },
{ title: 'Preprocessor', id: 20 },
{ title: 'String', id: 21 },
{ title: 'Structures', id: 22 },
{ title: 'Typedef', id: 23 },
{ title: 'Union', id: 24 }];
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
});
/////// html page /////////
<ion-view view-title="{{chat.title}}">
<ion-content class="padding">
{{chat.id}}
{{chat.desc}}
<div ng-include="{{chat.desc}}"></div>
</ion-content>
</ion-view>
Don't use the brackets for ng-include:
<div ng-include="chat.desc"></div>

Creating a basic data grid with Kendo UI and AngularJS

I'm experimenting with AngularJS. I want to show a basic Kendo Grid. I'm trying to do this using pure directives. With that in mind, I've looked at the Kendo UI / Angular JS project (https://github.com/kendo-labs/angular-kendo). Unfortunately, my
index.html:
<div>Products: {{products.length}}</div>
<div kendo-grid k-data-source="products" k-selectable="'row'"
k-pageable='{ "refresh": true, "pageSizes": true }'
k-columns='[
{ "field": "Name", "title": "Name"},
{ "field": "Department", "title": "Department"},
{ "field": "LastShipment", "title": "Last Shipment" }
]'>
</div>
controllers.js
function myController($scope) {
console.log("initializing controller...");
$scope.products = [
{ id:1, name:'Tennis Balls', department:'Sports', lastShipment:'10/01/2013' },
{ id:2, name:'Basket Balls', department:'Sports', lastShipment:'10/02/2013' },
{ id:3, name:'Oil', department:'Auto', lastShipment:'10/01/2013' },
{ id:4, name:'Filters', department:'Auto', lastShipment:'10/01/2013' },
{ id:5, name:'Dresser', department:'Home Furnishings', lastShipment:'10/01/2013' }
];
}
I've verified that I've wired up the controller properly. The activity count shows properly. However, the grid does not appear. I can't figure out what I'm doing incorrectly.
Thank you for your help.
You can also setup a Kendo DataSource as an AngularJS Service using the Factory method and inject this into your Controller to conform to AngularJS best practices and patterns.
Full source code and live demo: http://goo.gl/6Z9jop
Customer.cshtml
#{
ViewBag.Title = "Index";
}
<div>
<h2 ng-cloak>{{title}}</h2>
<div>
<div class="demo-section">
<div class="k-content" style="width: 100%">
<div kendo-grid="grid"
k-sortable="true"
k-pageable="true"
k-filterable="true"
k-editable="'inline'"
k-selectable="true"
k-columns='[
{ field: "CustomerID", title: "ID", width: "75px" },
{ field: "CompanyName", title: "Company"},
{ field: "ContactName", title: "Contact" },
{ field: "ContactTitle", title: "Title" },
{ field: "Address" },
{ field: "City" },
{ field: "PostalCode" },
{ field: "Country" },
{ field: "Phone" },
{ field: "Fax" }]'
>
</div>
<style scoped>
.toolbar { padding: 15px; float: right; }
</style>
</div>
</div>
<script type="text/x-kendo-template" id="toolbar">
<div>
<div class="toolbar">
<button kendo-button ng-click="edit(this)"><span class="k-icon k-i-tick"></span>Edit</button>
<button kendo-button ng-click="destroy(this)"><span class="k-icon k-i-tick"></span>Delete</button>
<button kendo-button ng-click="details(this)"><span class="k-icon k-i-tick"></span>Edit Details</button>
</div>
<div class="toolbar" style="display:none">
<button kendo-button ng-click="save(this)"><span class="k-icon k-i-tick"></span>Save</button>
<button kendo-button ng-click="cancel(this)"><span class="k-icon k-i-tick"></span>Cancel</button>
</div>
</div>
</script>
</div>
</div>
customerController.js
'use strict';
northwindApp.controller('customerController',
function ($scope, $rootScope, $location, customerDataSource)
{
customerDataSource.filter({}); // reset filter on dataSource everytime view is loaded
var onClick = function (event, delegate)
{
var grid = event.grid;
var selectedRow = grid.select();
var dataItem = grid.dataItem(selectedRow);
if (selectedRow.length > 0)
{
delegate(grid, selectedRow, dataItem);
}
else
{
alert("Please select a row.");
}
};
$scope.toolbarTemplate = kendo.template($("#toolbar").html());
$scope.save = function (e)
{
onClick(e, function (grid)
{
grid.saveRow();
$(".toolbar").toggle();
});
};
$scope.cancel = function (e)
{
onClick(e, function (grid)
{
grid.cancelRow();
$(".toolbar").toggle();
});
},
$scope.details = function (e)
{
onClick(e, function (grid, row, dataItem)
{
$location.url('/customer/edit/' + dataItem.CustomerID);
});
},
$scope.edit = function (e)
{
onClick(e, function (grid, row)
{
grid.editRow(row);
$(".toolbar").toggle();
});
},
$scope.destroy = function (e)
{
onClick(e, function (grid, row, dataItem)
{
grid.dataSource.remove(dataItem);
grid.dataSource.sync();
});
},
$scope.onChange = function (e)
{
var grid = e.sender;
$rootScope.lastSelectedDataItem = grid.dataItem(grid.select());
},
$scope.dataSource = customerDataSource;
$scope.onDataBound = function (e)
{
// check if there was a row that was selected
if ($rootScope.lastSelectedDataItem == null)
{
return;
}
var view = this.dataSource.view(); // get all the rows
for (var i = 0; i < view.length; i++)
{
// iterate through rows
if (view[i].CustomerID == $rootScope.lastSelectedDataItem.CustomerID)
{
// find row with the lastSelectedProductd
var grid = e.sender; // get the grid
grid.select(grid.table.find("tr[data-uid='" + view[i].uid + "']")); // set the selected row
break;
}
}
};
});
customerDataSource.js
'use strict';
northwindApp.factory('customerDataSource',
function (customerModel)
{
var crudServiceBaseUrl = "/odata/Customer";
return new kendo.data.DataSource({
type: "odata",
transport: {
read: {
async: false,
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: function (data)
{
return crudServiceBaseUrl + "(" + data.CustomerID + ")";
},
type: "put",
dataType: "json"
},
destroy: {
url: function (data)
{
return crudServiceBaseUrl + "(" + data.CustomerID + ")";
},
dataType: "json"
}
},
batch: false,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: function (data) { return data.value; },
total: function (data) { return data["odata.count"]; },
model: customerModel
},
error: function (e)
{
alert(e.xhr.responseText);
}
});
});
It looks as if the field names are spelled wrong. The following works for me:
<div kendo-grid k-data-source="products" k-selectable="'row'"
k-pageable='{ "pageSize": 2, "refresh": true, "pageSizes": true }'
k-columns='[
{ "field": "name", "title": "Name"},
{ "field": "department", "title": "Department"},
{ "field": "lastShipment", "title": "Last Shipment" }
]'>
</div>
Here is a live demo: http://jsbin.com/odeQAfI/2/edit
To avoid the NaN message in the pager you need to make the products field to be a Kendo DataSource:
function MyController($scope) {
$scope.products = new kendo.data.DataSource({
data: [
{ id:1, name:'Tennis Balls', department:'Sports', lastShipment:'10/01/2013' },
{ id:2, name:'Basket Balls', department:'Sports', lastShipment:'10/02/2013' },
{ id:3, name:'Oil', department:'Auto', lastShipment:'10/01/2013' },
{ id:4, name:'Filters', department:'Auto', lastShipment:'10/01/2013' },
{ id:5, name:'Dresser', department:'Home Furnishings', lastShipment:'10/01/2013' }
],
pageSize: 2
});
}
Here is a live demo: http://jsbin.com/ODElUfO/2/edit

Resources