Pass locals in mdBottomSheets(angular material bottom sheets) - angularjs

I have tried to pass locals in BottomSheet Controller
//Bottom Sheet Controller
angular
.module('app').controller('BottomSheetCtrl', function($scope, $mdBottomSheet) {
$scope.items = [
{ name: 'Share', icon: 'share-arrow' },
{ name: 'Upload', icon: 'upload' },
{ name: 'Copy', icon: 'copy' },
];
$scope.items.append($scope.Item);
console.log($scope.items);
});
//AppCtrl
angular
.module('app').controller('AppCtrl', function($scope, $mdBottomSheet){
$scope.openBottomSheet = function() {
$mdBottomSheet.show({
template:
'<md-bottom-sheet>{{}}</md-bottom-sheet>',
controller: 'BottomSheetCtrl',
scope: $scope.$new(true),
// preserveScope: true,
locals: {
Item: {
'name': 'Print this page', 'icon': 'print'
},
}
});
};
});
But $scope.Item is not populating. What is the correct way of passing locals in BottomSheet Controller?

You have to inject the locals into the bottom sheet controller - CodePen
Markup
<div ng-controller="BottomSheetExample" class="md-padding bottomSheetdemoBasicUsage" ng-cloak="" ng-app="MyApp">
<md-button flex="50" class="md-primary md-raised" ng-click="showListBottomSheet()">Show as List</md-button>
</div>
JS
angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('BottomSheetExample', function($scope, $timeout, $mdBottomSheet, $mdToast) {
$scope.showListBottomSheet = function() {
$scope.alert = '';
$mdBottomSheet.show({
template: '<md-bottom-sheet ng-cloak>{{Item.name}}</md-bottom-sheet>',
controller: 'ListBottomSheetCtrl',
locals: {
Item: {
'name': 'Print this page', 'icon': 'print'
},
}
}).then(function(clickedItem) {
$scope.alert = clickedItem['name'] + ' clicked!';
});
};
})
.controller('ListBottomSheetCtrl', function($scope, $mdBottomSheet, Item) {
console.log(Item);
$scope.Item = Item;
});
Bottom sheet reference
locals - {string=}: An object containing key/value pairs. The keys
will be used as names of values to inject into the controller. For
example, locals: {three: 3} would inject three into the controller
with the value of 3.

As an alternative you can also set the bindToController property to true. This allows accessing locals in the BottomSheetCtrl. So in the BottomSheetCtrl you can then get the value of Item like this:
var Item = this.locals.Item;
JS
//Bottom Sheet Controller
angular
.module('app').controller('BottomSheetCtrl', function($scope,
$mdBottomSheet) {
$scope.items = [
{ name: 'Share', icon: 'share-arrow' },
{ name: 'Upload', icon: 'upload' },
{ name: 'Copy', icon: 'copy' },
];
var Item = this.locals.Item;
$scope.items.append(Item);
console.log($scope.items);
});
//AppCtrl
angular
.module('app').controller('AppCtrl', function($scope, $mdBottomSheet){
$scope.openBottomSheet = function() {
$mdBottomSheet.show({
template:
'<md-bottom-sheet>{{}}</md-bottom-sheet>',
controller: 'BottomSheetCtrl',
scope: $scope.$new(true),
bindToController: true,
locals: {
Item: {
'name': 'Print this page', 'icon': 'print'
},
}
});
};
});

Related

angular dropdown multiselect to connect data between three dropdowns

I have three multiselect dropdowns:-
<label>Dropdown One</label>
<div ng-model="a.dp1" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownOne" extra-settings="multiSelectSettings">
</div>
<label>Dropdown Two</label>
<div ng-model="a.dp2" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownTwo" extra-settings="multiSelectSettings">
</div>
<label>Dropdown Three</label>
<div ng-model="a.dp3" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownThree" extra-settings="multiSelectSettings">
</div>
Directive Code:-
(function () {
'use strict';
angular.module('myApp.components')
.directive('page', page);
page.$inject = ['$http', '$timeout', 'ApiServices'];
function page($http, $timeout, ApiServices) {
return {
restrict: 'EA',
scope: {},
controller: function ($scope) {
$scope.a = { };
$scope.dropDownOne = [];
$scope.dropDownTwo = [];
$scope.dropDownThree = [];
$scope.multiSelectArray = [{
name: "Ayan"
}, {
name: "Rita"
}, {
name: "Mohit"
}, {
name: "Shittal"
}, {
name: "Jayant"
}, {
name: "Sachin"
}, {
name: "Tina"
}, {
name: "Babita"
}, {
name: "Priya"
}];
$scope.multiSelectSettings = {
smartButtonMaxItems: 11,
scrollable: true,
displayProp: "name",
idProp: "name",
externalIdProp: "name"
};
},
templateUrl: 'js/folder/system/page.html'
};
}
})();
What I am trying to do here is when I select particular options from 'Dropdown One' the same options got selected in 'Dropdown Two' and 'Dropdown Three' and get disabled so that users can't unselect them. Also, the users can select more options in 'Dropdown Two' and 'Dropdown Three' if they want, but the options from 'Dropdown One' should be checked already and disabled.
I am trying to disable the options using 'disabled' attribute but not able to for selected options. Any idea how I can do that?

How to resolve for angular ui-route

Here is my angularjs code. I have created different routes but i am unable to resolve my contract.dashboard route. If i remove the route object, it works fine but when i tried to reslove something from my service, it dose not work.
(function() {
'use strict';
angular
.module('app.contracts')
.run(appRun);
var _base = {
// Contract Base Contractor
contract: {
controllerAs: 'c',
controller: ['$scope', '$state', 'ContractModel', function($scope, $state, ContractModel){
'ngInject';
var that = this;
$scope.$watch(function(){ return $state.current.data.mode; }, function() { that.mode = $state.current.data.mode; });
that.contract = new ContractModel();
}]
}
};
/* #ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [
{
state: 'contract',
config: angular.extend({
abstract: true,
template: '<contract-manager><ui-view/></<contract-manager>',
url: '/contract'
}, _base.contract)
},
{
state: 'contract.new',
config: angular.extend({
url: '/new',
template: '<contract-editor mode="c.mode" contract="c.contract"></<contract-editor>',
title: 'Contract Editor',
data: {
mode: 'new'
}
}, _base.contract)
},
{
state: 'contract.dashboard',
config: angular.extend({
url: '',
template: '<contract-dashboard></contract-dashboard>',
title: 'Contract Dashboard',
data: {
mode:'dashboard'
},
resolve: {
stubs: function(stubs){
return stubs.service.registerGetCustomers();
}
}
}, _base.contract)
}
];
}
})();

injecting a list into a json format

I'm new with angularJs and i want to inject a list of string that i get it using a restful web service into a jSON list.
And how can the connections list could proceed object returned by getAllConnectedApp.
angular
.module('theme.core.navigation_controller', ['theme.core.services'])
.controller('NavigationController', ['$scope', '$location', '$timeout', '$filter', '$http', '$cookieStore', '$interval',
function($scope, $location, $timeout, filter, $http, $cookieStore, $interval) {
'use strict';
$scope.filterOptions = {
filterText: '',
useExternalFilter: true
};
$scope.connections = [];
$scope.menu = [{
label: 'HOME',
iconClasses: 'glyphicon glyphicon-home',
url: '#/'
}, {
label: 'ORACLE MONITORING',
iconClasses: 'glyphicon glyphicon-unchecked',
children: [{
label: 'SESSIONS',
url: '#/general'
}, {
label: 'ADVANCED MONITORING',
url: '#/advanced-monitoring'
}, {
label: 'CONFIGURATION',
url: '#/configuration'
}]
}, {
label: 'CODE TRACER',
iconClasses: 'glyphicon glyphicon-check',
children: [{
label: 'ADD CONNECTION',
url: '#/addConnectionApp'
},
for (var i = 0; i < $scope.connections.length; i++) {
{
label: $scope.connections[i],
url: '#/codetracer',
}
}
]
//url: '#/codetracer'
}];
$scope.getAllConnectedApp = function() {
console.log("GET ALL CONNECTED APPLICATIONS...");
$http.get("http://localhost:8090/api/personne/allConnection")
.success(function(connections) {
console.log(connections);
$scope.connections = connections;
});
};
}
]);
you have got syntax error over there, you can't have a loop inside object literal definition.
also, you portably want to update the menu only after getting back the response from the sever.
because your code was illogical as by the time you execute the loop, scope.connections is still an empty array.
something like this:
angular
.module('theme.core.navigation_controller', ['theme.core.services'])
.controller('NavigationController', ['$scope', '$location', '$timeout', '$filter', '$http', '$cookieStore', '$interval',
function ($scope, $location, $timeout, filter, $http, $cookieStore, $interval) {
'use strict';
$scope.filterOptions = {
filterText: '',
useExternalFilter: true
};
$scope.connections = [];
var connectionsMenu = [{
label: 'ADD CONNECTION',
url: '#/addConnectionApp'
}];
$scope.menu = [{
label: 'HOME',
iconClasses: 'glyphicon glyphicon-home',
url: '#/'
}, {
label: 'ORACLE MONITORING',
iconClasses: 'glyphicon glyphicon-unchecked',
children: [{
label: 'SESSIONS',
url: '#/general'
}, {
label: 'ADVANCED MONITORING',
url: '#/advanced-monitoring'
}, {
label: 'CONFIGURATION',
url: '#/configuration'
}]
}, {
label: 'CODE TRACER',
iconClasses: 'glyphicon glyphicon-check',
children: [connectionsMenu]
//url: '#/codetracer'
}];
$scope.getAllConnectedApp = function () {
console.log("GET ALL CONNECTED APPLICATIONS...");
$http.get("http://localhost:8090/api/personne/allConnection")
.success(function (connections) {
console.log(connections);
$scope.connections = connections;
for (var i = 0; i < connections.length; i++) {
connectionsMenu.push({
label: connections[i],
url: '#/codetracer',
});
}
});
};
}
]);

ng-repeat do not evaluate from $sce.trustAsHtml inside directive

I have a directive that has a piece of custom HTML that I can pass in as a custom option. I would like to use ng-repeat inside the custom HTML, but it is not being displayed. Here is the code.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.local = {
options: {
columns: [{
name: 'product_id',
label: 'Product ID'
}, {
name: 'product_name',
label: 'Name'
}],
getBody: function( col, i ) {
return col.name == 'product_id' ? col.label : '<div class="dropdown product-status"><button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Status<span class="caret"></span></button><span class="dropdown-arrow"></span><ul class="dropdown-menu"><li ng-repeat="one_status in dataset.status"><a class="status all" ng-click="dataset.updateStatus(one_status.status_id)" ng-bind="one_status.status_name"></a></li></ul></div>';
}
},
dataset: {
status: [{
status_id: 1,
status_name: 'first draft'
}, {
status_id: 2,
status_name: 'in edit'
}]
}
};
});
app.directive('test', function($sce) {
var linkFunc = function(scope) {
scope.getBody = function( col, index ) {
return $sce.trustAsHtml( scope.options.getBody( col, index ) );
};
};
return {
link: linkFunc,
scope: {
options: '=',
dataset: '='
},
templateUrl: 'test.html'
};
});
http://plnkr.co/edit/mCynQWtQElTGfoLXZHqZ?p=preview
you need to make sure $sce is in a part of your controller
check this out
-- http://jsfiddle.net/3J25M/2/
.controller('ngBindHtmlCtrl', ['$scope','$sce', function ngBindHtmlCtrl($scope, $sce)
...etc
also, check this question out: AngularJS using $sce.trustAsHtml with ng-repeat

AngularJS nested routes example questions

Any explanation why the sample code (ui-router/sample/index.html) for angular-ui-router (https://github.com/angular-ui/ui-router) looks like this. Specifically:
Why the nested definitions of objects like controllers?
Why the specification of dependencies like this:
angular.module('sample', ['ui.compat'])
.config(
[ '$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
thanks
<!doctype html>
<html lang="en" ng-app="sample"><head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<style type="text/css">
.fade-enter-setup, .fade-leave-setup {
transition: opacity 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0s;
}
.fade-enter-setup,
.fade-leave-setup.fade-leave-start {
opacity: 0;
}
.fade-leave-setup,
.fade-enter-setup.fade-enter-start {
opacity: 1;
}
</style>
<script src="../lib/angular-1.1.4.js"></script>
<script src="../build/angular-ui-router.js"></script>
<!-- could easily use a custom property of the state here instead of 'name' -->
<title ng-bind="$state.current.name + ' - ui-router'">ui-router</title>
</head><body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner"><div class="container">
<a class="brand" href="#">ui-router</a>
<ul class="nav">
<li ng-class="{ active: $state.includes('contacts') }">Contacts</li>
<li ng-class="{ active: $state.includes('about') }">About</li>
</ul>
<p class="navbar-text pull-right" ui-view="hint"></p>
</div></div>
</div>
<div class="container" style="margin-top:60px" ui-view ng-animate="{enter:'fade-enter'}"></div>
<hr>
<pre>
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
</pre>
</body><script>
function findById(a, id) {
for (var i=0; i<a.length; i++) {
if (a[i].id == id) return a[i];
}
}
angular.module('sample', ['ui.compat'])
.config(
[ '$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
$urlRouterProvider
.when('/c?id', '/contacts/:id')
.otherwise('/');
$routeProvider
.when('/user/:id', {
redirectTo: '/contacts/:id',
})
.when('/', {
template: '<p class="lead">Welcome to the ngStates sample</p><p>Use the menu above to navigate</p>' +
'<p>Look at Alice or Bob to see a URL with a redirect in action.</p>',
});
$stateProvider
.state('contacts', {
url: '/contacts',
abstract: true,
templateUrl: 'contacts.html',
controller:
[ '$scope', '$state',
function ($scope, $state) {
$scope.contacts = [{
id: 1,
name: "Alice",
items: [{
id: 'a',
type: 'phone number',
value: '555-1234-1234',
},{
id: 'b',
type: 'email',
value: 'alice#mailinator.com',
}],
}, {
id: 42,
name: "Bob",
items: [{
id: 'a',
type: 'blog',
value: 'http://bob.blogger.com',
},{
id: 'b',
type: 'fax',
value: '555-999-9999',
}],
}, {
id: 123,
name: "Eve",
items: [{
id: 'a',
type: 'full name',
value: 'Eve Adamsdottir',
}],
}];
$scope.goToRandom = function () {
var contacts = $scope.contacts, id;
do {
id = contacts[Math.floor(contacts.length * Math.random())].id;
} while (id == $state.params.contactId);
$state.transitionTo('contacts.detail', { contactId: id });
};
}],
})
.state('contacts.list', {
// parent: 'contacts',
url: '',
templateUrl: 'contacts.list.html',
})
.state('contacts.detail', {
// parent: 'contacts',
url: '/{contactId}',
resolve: {
something:
[ '$timeout', '$stateParams',
function ($timeout, $stateParams) {
return $timeout(function () { return "Asynchronously resolved data (" + $stateParams.contactId + ")" }, 10);
}],
},
views: {
'': {
templateUrl: 'contacts.detail.html',
controller:
[ '$scope', '$stateParams', 'something',
function ($scope, $stateParams, something) {
$scope.something = something;
$scope.contact = findById($scope.contacts, $stateParams.contactId);
}],
},
'hint#': {
template: 'This is contacts.detail populating the view "hint#"',
},
'menu': {
templateProvider:
[ '$stateParams',
function ($stateParams){
// This is just to demonstrate that $stateParams injection works for templateProvider
// $stateParams are the parameters for the new state we're transitioning to, even
// though the global '$stateParams' has not been updated yet.
return '<hr><small class="muted">Contact ID: ' + $stateParams.contactId + '</small>';
}],
},
},
})
.state('contacts.detail.item', {
// parent: 'contacts.detail',
url: '/item/:itemId',
views: {
'': {
templateUrl: 'contacts.detail.item.html',
controller:
[ '$scope', '$stateParams', '$state',
function ($scope, $stateParams, $state) {
$scope.item = findById($scope.contact.items, $stateParams.itemId);
$scope.edit = function () {
$state.transitionTo('contacts.detail.item.edit', $stateParams);
};
}],
},
'hint#': {
template: 'Overriding the view "hint#"',
},
},
})
.state('contacts.detail.item.edit', {
views: {
'#contacts.detail': {
templateUrl: 'contacts.detail.item.edit.html',
controller:
[ '$scope', '$stateParams', '$state',
function ($scope, $stateParams, $state) {
$scope.item = findById($scope.contact.items, $stateParams.itemId);
$scope.done = function () {
$state.transitionTo('contacts.detail.item', $stateParams);
};
}],
},
},
})
.state('about', {
url: '/about',
templateProvider:
[ '$timeout',
function ($timeout) {
return $timeout(function () { return "Hello world" }, 100);
}],
})
.state('empty', {
url: '/empty',
templateUrl: 'empty.html',
controller:
[ '$scope', '$state',
function ($scope, $state) {
// Using an object to access it via ng-model from child scope
$scope.data = {
initialViewTitle: "I am an initial view"
}
$scope.changeInitialViewTitle = function($event) {
$state.transitionTo('empty.emptycontent');
};
$scope.showInitialView = function($event) {
$state.transitionTo('empty');
};
}]
})
.state('empty.emptycontent', {
url: '/content',
views: {
'emptycontent': {
templateUrl: 'empty.content.html'
}
}
});
}])
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}]);
</script></html>
ui-router doesn't fully support this. You may check this library for nested routing: http://angular-route-segment.com
It provides the functionality for creating tree-like routing hierarchy which can be changed without losing the state.
$routeSegmentProvider.
when('/section1', 's1.home').
when('/section1/prefs', 's1.prefs').
when('/section1/:id', 's1.itemInfo.overview').
when('/section1/:id/edit', 's1.itemInfo.edit').
when('/section2', 's2').
segment('s1', {
templateUrl: 'templates/section1.html',
controller: MainCtrl}).
within().
segment('home', {
templateUrl: 'templates/section1/home.html'}).
segment('itemInfo', {
templateUrl: 'templates/section1/item.html',
controller: Section1ItemCtrl,
dependencies: ['id']}).
within().
segment('overview', {
templateUrl: 'templates/section1/item/overview.html'}).
segment('edit', {
templateUrl: 'templates/section1/item/edit.html'}).
up().
segment('prefs', {
templateUrl: 'templates/section1/prefs.html'}).
up().
segment('s2', {
templateUrl: 'templates/section2.html',
controller: MainCtrl});
The nesting is only one way of doing the example. you could write
'navTitle#': {
templateUrl : 'pages/mypage.html',
controller: 'myController',
},
and then just define myController anywhere else you want in your app.
function myController ($scope) {
};
as far as dependencies question...thats one way of injecting in dependancies in angular so you can reuse the code in other places.
.factory('appLoading', function($rootScope, $state) {
return {
loading : function() {
$rootScope.status = 'loading';
if(!$rootScope.$$phase) $rootScope.$apply();
},
ready : function(delay) {
function ready() {
$rootScope.status = 'ready';
$rootScope.title = $state.current.data.title;
if(!$rootScope.$$phase) $rootScope.$apply();
}
}
};
})
then if i wanted to call this loader in a module it would go inside []
like inside the onExit of a state inside ui-router...
onExit: ['appLoading',
function ( appLoading) {
appLoading.loading();
}],

Resources