save and cancel button is not working - javascript

I've created an application in angular js for add and remove popup model, The popup model is coming
but on saving i'm getting undefined and cancel is not working .
JSFIDDLE
can anyone please tell me some solution for this
var app = angular.module('mainApp', ['commonApp', 'ui.bootstrap']);
app.controller('mainController', function ($scope, $rootScope, $modal, $log) {
$scope.users = [{
userId: 1,
userName: "Jhonny"
}, {
userId: 2,
userName: "Sunny"
}];
$scope.selectedUsers = {
users: []
};
$scope.open = function (users, dept) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'mainController',
resolve: {
usersInModalScope: function () {
return users;
},
deptInModalScope: function () {
return dept;
}
}
});
};
});
var commonApp = angular.module('commonApp', ['ui.bootstrap']);
commonApp.controller('ModalInstanceCtrl', function ($scope, $rootScope) {
$scope.cancel = function () {
$scope.modalInstance.close();
if ($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest') {
$rootScope.$apply();
}
}
$scope.save = function () {
alert(JSON.stringify($scope.selectedUsers));
}
});
commonApp.directive('multiSelect', function ($q) {
return {
restrict: 'E',
controller: "ModalInstanceCtrl",
require: 'ngModel',
scope: {
selectedLabel: "#",
availableLabel: "#",
displayAttr: "#",
available: "=",
model: "=ngModel",
eventHandler: '&ngClick'
},
template: '<div class="multiSelect">' +
'<div class="select">' +
'<label class="control-label" for="multiSelectAvailable">{{ availableLabel }} ' +
'({{ available.length }})</label>' +
'<select id="multiSelectAvailable" ng-model="selected.available" multiple ' +
'ng-options="e as e[displayAttr] for e in available"></select>' +
'</div>' +
'<div class="select buttons">' +
'<button class="btn mover right" ng-click="add()" title="Add selected" ' +
'ng-disabled="selected.available.length == 0">' +
'<i class=" icon-arrow-right"></i>' +
'</button>' +
'<button class="btn mover left" ng-click="remove()" title="Remove selected" ' +
'ng-disabled="selected.current.length == 0">' +
'<i class="icon-arrow-left"></i>' +
'</button>' +
'</div>' +
'<div class="select">' +
'<label class="control-label" for="multiSelectSelected">{{ selectedLabel }} ' +
'({{ model.length }})</label>' +
'<select id="currentRoles" ng-model="selected.current" multiple ' +
'class="pull-left" ng-options="e as e[displayAttr] for e in model">' +
'</select>' +
'</div>' +
'</div>' +
'<div class="wrapper text-center">' +
'<button class="btn btn-default" ng-click="save()"> Save </button>' +
'<button class="btn btn-default" ng-click="cancel()">Cancel</button>' +
'</div>',
link: function (scope, elm, attrs) {
scope.selected = {
available: [],
current: []
};
var dataLoading = function (scopeAttr) {
var loading = $q.defer();
if (scope[scopeAttr]) {
loading.resolve(scope[scopeAttr]);
} else {
scope.$watch(scopeAttr, function (newValue, oldValue) {
if (newValue !== undefined) loading.resolve(newValue);
});
}
return loading.promise;
};
var filterOut = function (original, toFilter) {
var filtered = [];
angular.forEach(original, function (entity) {
var match = false;
for (var i = 0; i < toFilter.length; i++) {
if (toFilter[i][attrs.displayAttr] == entity[attrs.displayAttr]) {
match = true;
break;
}
}
if (!match) {
filtered.push(entity);
}
});
return filtered;
};
scope.refreshAvailable = function () {
scope.available = filterOut(scope.available, scope.model);
scope.selected.available = [];
scope.selected.current = [];
};
scope.add = function () {
scope.model = scope.model.concat(scope.selected.available);
scope.refreshAvailable();
};
scope.remove = function () {
scope.available = scope.available.concat(scope.selected.current);
scope.model = filterOut(scope.model, scope.selected.current);
scope.refreshAvailable();
};
$q.all([dataLoading("model"), dataLoading("available")]).then(function (results) {
scope.refreshAvailable();
});
}
};
})

Here
Working Demo $rootScope
Working Demo Factory Version
Problem with controller's scope.mainController and ModalInstanceCtrl have their own scope. it is not same scope instance totally different so here $rootScope is same instance across app.
First working demo I'm using $rootScope variable. Depending on global object really bad design.
To communicate between controllers you need to create factory service like userFactory then pass around your controllers. In factory service keep your modal.
var app = angular.module('mainApp', ['commonApp', 'ui.bootstrap']);
app.controller('mainController', function ($scope, $rootScope, $modal, $log, userFactory) {
$scope.users = userFactory.users;
$scope.selectedUsers = userFactory.selectedUsers;
$scope.open = function (users, dept) {
userFactory.modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'mainController',
resolve: {
usersInModalScope: function () {
return userFactory.users;
},
deptInModalScope: function () {
return userFactory.dept;
}
}
});
};
});
app.factory('userFactory', function (){
return {
modalInstance:{},
users : [{
userId: 1,
userName: "Jhonny"
},
{
userId: 2,
userName: "Sunny"
}
],
selectedUsers :{users: []},
dept : [],
}
});
var commonApp = angular.module('commonApp', ['ui.bootstrap']);
commonApp.controller('ModalInstanceCtrl', function ($scope, $rootScope, userFactory) {
$scope.cancel = function () {
userFactory.modalInstance.close();
if ($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest') {
$rootScope.$apply();
}
}
$scope.save = function () {
alert(JSON.stringify(userFactory.selectedUsers));
}
});
commonApp.directive('multiSelect', function ($q) {
return {
restrict: 'E',
controller: "ModalInstanceCtrl",
require: 'ngModel',
scope: {
selectedLabel: "#",
availableLabel: "#",
displayAttr: "#",
available: "=",
model: "=ngModel",
eventHandler: '&ngClick'
},
template: '<div class="multiSelect">' +
'<div class="select">' +
'<label class="control-label" for="multiSelectAvailable">{{ availableLabel }} ' +
'({{ available.length }})</label>' +
'<select id="multiSelectAvailable" ng-model="selected.available" multiple ' +
'ng-options="e as e[displayAttr] for e in available"></select>' +
'</div>' +
'<div class="select buttons">' +
'<button class="btn mover right" ng-click="add()" title="Add selected" ' +
'ng-disabled="selected.available.length == 0">' +
'<i class=" icon-arrow-right"></i>' +
'</button>' +
'<button class="btn mover left" ng-click="remove()" title="Remove selected" ' +
'ng-disabled="selected.current.length == 0">' +
'<i class="icon-arrow-left"></i>' +
'</button>' +
'</div>' +
'<div class="select">' +
'<label class="control-label" for="multiSelectSelected">{{ selectedLabel }} ' +
'({{ model.length }})</label>' +
'<select id="currentRoles" ng-model="selected.current" multiple ' +
'class="pull-left" ng-options="e as e[displayAttr] for e in model">' +
'</select>' +
'</div>' +
'</div>' +
'<div class="wrapper text-center">' +
'<button class="btn btn-default" ng-click="save()"> Save </button>' +
'<button class="btn btn-default" ng-click="cancel()">Cancel</button>' +
'</div>',
link: function (scope, elm, attrs) {
scope.selected = {
available: [],
current: []
};
var dataLoading = function (scopeAttr) {
var loading = $q.defer();
if (scope[scopeAttr]) {
loading.resolve(scope[scopeAttr]);
} else {
scope.$watch(scopeAttr, function (newValue, oldValue) {
if (newValue !== undefined) loading.resolve(newValue);
});
}
return loading.promise;
};
var filterOut = function (original, toFilter) {
var filtered = [];
angular.forEach(original, function (entity) {
var match = false;
for (var i = 0; i < toFilter.length; i++) {
if (toFilter[i][attrs.displayAttr] == entity[attrs.displayAttr]) {
match = true;
break;
}
}
if (!match) {
filtered.push(entity);
}
});
return filtered;
};
scope.refreshAvailable = function () {
scope.available = filterOut(scope.available, scope.model);
scope.selected.available = [];
scope.selected.current = [];
};
scope.add = function () {
scope.model = scope.model.concat(scope.selected.available);
scope.refreshAvailable();
};
scope.remove = function () {
scope.available = scope.available.concat(scope.selected.current);
scope.model = filterOut(scope.model, scope.selected.current);
scope.refreshAvailable();
};
$q.all([dataLoading("model"), dataLoading("available")]).then(function (results) {
scope.refreshAvailable();
});
}
};
})

I am pretty sure you need to reference the modalInstanceController when you create the modal and not the mainController.
$scope.open = function (users, dept) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
usersInModalScope: function () {
return users;
},
deptInModalScope: function () {
return dept;
}
}
});
};
And you need to pass you resolutions into the parameters of the controller as well, also the $modalInstance service is where the methods close, dismiss, etc live...
commonApp.controller('ModalInstanceCtrl', function ($scope, $rootScope, $modalInstance, usersInModalScope, deptInModalScope) {
$scope.cancel = function () {
$modalInstance.close();
}
$scope.save = function () {
alert(JSON.stringify($scope.selectedUsers));
}
});
Now having said this I couldnt get your implementation to work the way you want it. But in our implementation of the ui.bootstrap and the modals we use this version.
ProductsCtrl
angular.module('app', ['ui.bootstrap'])
.controller('AppController', function($scope, $modal, $templateCache) {
$scope.product = { product: 'I am the product' };
$scope.openEditProductModal = function () {
var editProductModal = $modal.open({
templateUrl: 'edit-product.html',
controller: 'EditProductModalController',
resolve: {
product: function () {
return $scope.product;
}
}
});
editProductModal.result.then(function (product) {
$scope.product = product;
});
};
})
Modal Controller
.controller('EditProductModalController', function ($scope, $modalInstance, product) {
$scope.product = product;
$scope.ok = function () {
/**
* Set the edited description and close the modal resolving the promise
*/
$scope.product = product
$modalInstance.close($scope.product);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
})
HTML
<body ng-controller="AppController">
<h1 ng-bind="product.product"></h1>
<br>
<button ng-click="openEditProductModal(product.product)">Open Modal</button>
<br>
<span ng-bind="product.product"></span>
</body>
Edit-Product.html
<div class="modal-header">
<h3><span class="glyphicon glyphicon-edit"></span> Edit Product</h3>
<span class="subtitle" ng-bind="product.name"></span>
</div>
<div class="modal-body edit-description-modal">
<div class="row">
<input ng-model="product.product"/>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">Save</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
Link to Plunkr

Related

Send parameters from directive to controllers in AngularJS

Inside oferta-ut.controller.js I need to change state from main.ut.ofertas to main.ut.resumen. Then select something and call scope.clickAction inside ut-result.directive.js. This action should send parameters to oferta-ut.controller.js so I can use it with others parameters to go to another state.
Here goes some code
servicio-ut.controller.js
$state.go('main.ut.ofertas', {
plan: $stateParams.plan,
destino: $stateParams.destino,
fechaEntrada: $stateParams.fechaEntrada,
fechaSalida: $stateParams.fechaSalida,
duracion: $stateParams.duracion,
huespedes: $stateParams.huespedes,
servicio: ctrl.servicioInc,
});
oferta-ut.controller.js
'use strict';
function ofertasUtCtrl($scope, $stateParams, $state,
unidadTuristicaService, moment, util, SessionService, $analytics, $window) {
'ngInject';
var ctrl = this,
if (!$stateParams.servicio) {
$state.go('main.home');
} else {
ctrl.ofertaSeleccionada=null;
activate();
}
function activate() {
var fechaEntrada = $stateParams.fechaEntrada.getFullYear() + "-" +
($stateParams.fechaEntrada.getMonth() + 1) + "-" +
$stateParams.fechaEntrada.getDate();
var fechaSalida = $stateParams.fechaSalida.getFullYear() + "-" +
($stateParams.fechaSalida.getMonth() + 1) + "-" +
$stateParams.fechaSalida.getDate();
unidadTuristicaService.obtenerOfertasUt(
$stateParams.plan.id,$stateParams.servicio.code,
$stateParams.destino.id,
fechaEntrada,
fechaSalida,
$stateParams.duracion.id)
.then(function(ofertas){
for(var clave in ofertas.resultadoBusquedaUt){
ofertas.resultadoBusquedaUt[clave].fechaDesde = moment(fechaEntrada).format('DD/MM/YYYY');
ofertas.resultadoBusquedaUt[clave].fechaHasta = moment(fechaSalida).format('DD/MM/YYYY');
}
ctrl.ofertas = ofertas;
});
}
ctrl.confirmarServ = function() {
$analytics.eventTrack("Clic Siguiente", {
category: 'UT',
label: "Clic Servicios UT"
});
$state.go('main.ut.resumen', {
plan: $stateParams.plan,
destino: $stateParams.destino,
fechaEntrada: ctrl.fechaEntrada,
fechaSalida: ctrl.fechaSalida,
huespedes: ctrl.cantHuespuedes,
duracion: $stateParams.duracion,
servicio: ctrl.servicioInc
});
};
}
module.exports = ofertasUtCtrl;
The view for the action is this one
<div flex>
<pager results="ctrl.ofertas.resultadoBusquedaUt" per-page="10" result-type="UT"></pager>
</div>
ut-result.directive.js
"use strict";
var utResultView = require('./ut-result.view.html'),
imgPlaceHolder = require('../../img/hotel_holder.png');
function hotelResult(util, $state, moment) {
'ngInject';
var directive = {
templateUrl: utResultView,
restrict: 'EA',
scope: {
model: '=',
params: '<'
},
link: link
};
return directive;
function link(scope) {
scope.icono = mapearIcono;
scope.filterHide = function() {
// ver si está filtrado por algun criterio
return scope.model.filterHide && scope.model.filterHide.length > 0;
};
var unbindWatch = scope.$watch("model", function(oldV, newV) {
if (newV) {
activate();
}
});
function activate() {
// iterador para estrellitas
scope.estrellas = [1,2,3,4,5].slice(0, scope.model.estrellas);
//Categoria UT
scope.categoriaUt = scope.model.categoriasUt;
scope.datosPrestador = scope.model.razonSocial + ' - CUIT: ' + scope.model.cuit;
scope.imgSrc = scope.model.urlImagen || imgPlaceHolder;
scope.imgError = imgPlaceHolder;
scope.precio = scope.model.precio? util.formatCurrency(scope.model.precio) : null;
scope.clickAction = function(model) {
// THIS ACTION
};
}
}
module.exports = hotelResult;

Modify ng-show within directive template from link

I have a directive element:
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<ul>' +
'<li ng-show="hideItem">Home</li>' +
'<li ng-show="hideItem">Products</li>' +
'<li ng-show="!hideItem">Cart</li>' +
'<li ng-show="hideItem">Contact Us</li>' +
'</ul>',
link: function(scope, element, attrs) {
var shouldHide = myService.getData();
if (shouldHide === true) {
scope.hideItem = true
}
}
};
The link function performs a call to a service, the result is either true or false.
If true, i want hideItem to be set to true within my ng-show.
HTML structure:
<section ng-controller="NavigationController">
<i class="home"></i>
<i class="bell"></i>
<i class="phone"></i>
<my-directive></my-directive>
<button>Submit</button>
</section>
DEMO
you can actually just vm.hideItem = myService.getData(); since you want the boolean's value anyway
return {
restrict: 'E',
replace: true,
controllerAs: 'vm',
transclude: true,
template: '<ul>' +
'<li ng-show="vm.hideItem">Home</li>' +
'<li ng-show="vm.hideItem">Products</li>' +
'<li ng-show="!vm.hideItem">Cart</li>' +
'<li ng-show="vm.hideItem">Contact Us</li>' +
'</ul>',
link: function(scope, element, attrs, vm) {
vm.hideItem = myService.getData();
},
controller: function(){
}
};
I added controllerAs: 'vm' it's much more manageable by assigning a name to your controller and attach variables to it
You have to watch it :
scope.$watch(function(){
return myService.getData();
}, function(newValue){
scope.hideItem = newValue;
});
This is only if your service is not doing server-side requests, otherwise you'll spam the server.
I think getData method can be called from anywhere in your application.
And you want to keep track of these changes in your directive. In this case, you can use the callback.
Live example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, myService) {
$scope.resolve = function() {
myService.getData().then(function() {
console.log('resolved from button resolve');
})
}
myService.getData().then(function() {
console.log('resolved from controller loading');
})
})
.directive('exampleDirective', function(myService) {
return {
restrict: "E",
scope: {
value: "="
},
template: `<div>hidden={{hidden}} value={{value}} <span ng-show="hidden">ng-show="hidden"</span><span ng-show="!hidden">ng-show="!hidden"</span></div>`,
link: function(scope) {
scope.hidden = false;
myService.addCallback(function(hideItem) {
scope.hidden = hideItem;
console.log('callback resolved with value ' + scope.value + ' and hide is ' + hideItem);
});
}
}
})
.service('myService', function($q, $timeout) {
var callbacks = [];
return {
getData: function() {
var defered = $q.defer();
//simulate $http call
$timeout(function() {
defered.resolve();
//simulate answer from server
var res = Math.round(Math.random() * 10) >= 5;
angular.forEach(callbacks, function(c) {
//call callback with result
$q.resolve(res, c);
});
}, 1000);
return defered.promise;
},
addCallback: function(callback) {
callbacks.push(callback);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController" id="ExampleController">
<button ng-click="resolve()">
call getData
</button>
<example-directive value="12"></example-directive>
<example-directive value="'ab'"></example-directive>
</div>
</div>
When you anywhere using the method of your getData directive knows that.

switch between 2 angulrjs tabs that using same controller

i am using angularjs-ui tabs in my app.
angular.module('bootstrap.tabset', [])
.directive('tekplntabsets',['tabsetServ', function (tabsetServ) {
return {
restrict: 'E',
replace: true,
transclude: true,
controller: function ($scope) {
$scope.templateUrl = '';
var tabs = $scope.tabs = [];
var controller = this;
this.selectTab = function (tab) {
angular.forEach(tabs, function (tab) {
tab.selected = false;
});
tab.selected = true;
tabsetServ.setTabId(tab.tabid);
};
this.setTabTemplate = function(templateUrl) {
$scope.templateUrl = templateUrl;
};
this.setTabController = function(tabCtrl) {
$scope.tabCtrl = tabCtrl;
};
this.getTabController = function() {
return $scope.tabCtrl;
};
this.removeTab = function(tab) {
var index = tabsetServ.removeTab(tab);
this.selectTab(tabs[index - 1]);
};
this.addTab = function (tab) {
if (tabs.length == 0) {
controller.selectTab(tab);
}
tabs.push(tab);
controller.selectTab(tab);
};
},
template:
'<div class="row-fluid flexbox flexboxContent divHeight100">' +
'<div class="row-fluid">' +
'<div class="nav nav-tabs" ng-transclude></div>' +
'</div>' +
'<div class="row-fluid flexbox flexboxContent divHeight100">' +
'<ng-include src="templateUrl" class="flexbox flexboxContent divHeight100" ></ng-include>' +
'</div>' +
'</div>'
};
}])
.directive('tekplntab', function () {
return {
restrict: 'E',
replace: true,
require: '^tekplntabsets',
scope: {
title: '#',
templateUrl: '#',
tabid: '#',
closable: '#',
tabicon: '#',
controller:'#'
},
link: function (scope, element, attrs, tabsetController, $route) {
tabsetController.addTab(scope);
scope.select = function () {
tabsetController.selectTab(scope);
};
scope.$watch('selected', function () {
if (scope.selected) {
tabsetController.setTabTemplate('');
tabsetController.setTabTemplate(scope.templateUrl);
// scope.$apply();
//$route.reload();
//if (scope.$parent.tektab.ctrl !== "" && scope.$parent.tektab.ctrl !== "DashboardCtrl") {
// var ctrl = scope.$parent.tektab.ctrl;
// scope.$parent.tektab.ctrl = "";
// scope.$parent.tektab.ctrl = ctrl;
//}
//if (scope.$root.$$phase !== '$digest' && scope.$$phase !== '$digest') {
// scope.$apply();
// }
//scope.$watch('scope.tabid', function (randomValue) {
// scope.$apply();
//}); ng-controller="{{controller}}"
}
});
scope.removeTab = function (id) {
tabsetController.removeTab(id);
};
},
template:
'<li ng-class="{active: selected}" >' +
'<a href="" ng-click="select()"><div class="pointerDiv {{ tabicon }}" ng-show="{{closable}}"></div> {{ title }} ' +
'<button ng-click="removeTab(title)" class="TabClose" ng-show="{{closable}}">x</button></a>' +
'<input type="hidden" value="{{ tabid }}"></input>' +
'</li>'
};
});
When I am using this directive to open 2 tabs that use different controllers it works well.
The problem occurs when I want to switch between 2 tabs that using same controller. (for example, when I open 2 different projects and I want to switch between project number 1 and project number 2, the tab does not load all the data from project number 2 !!).
I don't want to use angular-ui-router.
project 1 and project 2 uses same partial html
I managed to solve the problem by using Boradcasting messages

Why I get error when I try to use custom directive.

I am using this link to implement DropdownmultiSelect in my tutorial project.
Here how I define directive at my tutorial project:
(function () {
"use strict";
angular.module("gameBuilder").directive('dropdownMultiselect', [dropdownMultiselect]);
function dropdownMultiselect() {
return {
restrict: 'E',
scope: {
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div class='btn-group' data-ng-class='{open: open}'>" +
"<button class='btn btn-small'>Select</button>" +
"<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>" +
"<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
"<li><a data-ng-click='selectAll()'><i class='icon-ok-sign'></i> Check All</a></li>" +
"<li><a data-ng-click='deselectAll();'><i class='icon-remove-sign'></i> Uncheck All</a></li>" +
"<li class='divider'></li>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>",
controller: function ($scope) {
$scope.openDropdown = function () {
$scope.selected_items = [];
for (var i = 0; i < $scope.pre_selected.length; i++) {
$scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.selectAll = function () {
$scope.model = _.pluck($scope.options, 'id');
console.log($scope.model);
};
$scope.deselectAll = function () {
$scope.model = [];
console.log($scope.model);
};
$scope.setSelectedItem = function () {
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'icon-ok pull-right';
}
return false;
};
}
}
}
})();
Here is controller definition:
(function () {
"use strict";
angular.module("gameBuilder", ["ui.router", "templates"])
.config([
"$stateProvider",
function ($stateProvider) {
$stateProvider
.state("gameBuilder", {
abstract: true,
url: "/gameBuilder",
template: "<ui-view></ui-view>"
})
.state("gameBuilder.list", {
url: "/",
templateUrl: "app/gameBuilder/templates/gameBuilderList.tmpl.html",
controller: "gameBuilderListController",
controllerAs: "list"
})
.state("gameBuilder.view", {
url: "/:gameId",
templateUrl: "app/gameBuilder/templates/gameBuilder.tmpl.html",
controller: "gameBuilderController",
controllerAs: "builder"
})
.state("gameBuilder.view.step1", {
url: '/step1',
templateUrl: "../app/gameBuilder/templates/NestedViews/FormStep1.html"
})
.state("gameBuilder.view.step2", {
url: '/step2',
templateUrl: "../app/gameBuilder/templates/NestedViews/FormStep2.html"
})
.state("gameBuilder.view.step3", {
url: '/step3',
templateUrl: "../app/gameBuilder/templates/NestedViews/FormStep3.html"
});
}
]);
})();
Here is how I use it in view:
<div class="form-group">
<dropdown-multiselect pre-selected="game.member.roles" model="game.selected_items" options="game.roles"></dropdown-multiselect>
<pre>
selected roles = {{game.selected_items | json}}
</pre>
</div>
But I get this error:
ReferenceError: _ is not defined
at Scope.$scope.isChecked (inspectionsBuilder.js:150)
at Object.$parseFunctionCall [as get] (angular.js:12332)
at Scope.$digest (angular.js:14217)
at Scope.$apply (angular.js:14488)
at done (angular.js:9646)
at completeRequest (angular.js:9836)
at XMLHttpRequest.requestLoaded (angular.js:9777)
Have you included underscore/lo-dash?
"ReferenceError: _ is not defined" usually appears when you haven't loaded library
You made a typo inside your isolate scope declaration, It should be preSelected instead of pre_selectedfollow the camel-casing also replace the $scope.pre_selected with $scope.preSelected
Code
scope: {
model: '=',
options: '=',
preSelected: '=preSelected' //<--change here
},

Change url when switching tabs using Angularjs

I am trying to modify the last example (Create Components) on http://angularjs.org/ so that when switching the tab, the url will change. The complete code:
angular.module('components', [])
.directive('tabs', function ($location) {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: function ($scope, $element) {
var panes = $scope.panes = [];
$scope.$watch(function () {
return $location.path();
}, function (url) {
//select pane
});
$scope.select = function (pane) {
angular.forEach(panes, function (eachPane, key) {
eachPane.selected = false;
if (pane == eachPane) {
if (key == "1") {
$location.path("Pluralization");
} else {
$location.path("Localization");
}
}
});
pane.selected = true;
};
this.addPane = function (pane) {
panes.push(pane);
console.log("addPane");
if (panes.length == 2) {
if ($location.path() == "/Pluralization") {
$scope.select(panes[1]);
} else {
$scope.select(panes[0]);
}
}
}
},
template:
'<div class="tabbable">' +
'<ul class="nav nav-tabs">' +
'<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">' +
'{{pane.title}}' +
'</li>' +
'</ul>' +
'<div class="tab-content" ng-transclude></div>' +
'</div>',
replace: true
};
})
.directive('pane', function () {
return {
require: '^tabs',
restrict: 'E',
transclude: true,
scope: {
title: '#'
},
link: function (scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
template:
'<div class="tab-pane" ng-class="{active: selected}" ng-transclude>' +
'</div>',
replace: true
};
})
angular.module('app', ['components'])
.controller('BeerCounter', function ($scope, $locale) {
$scope.beers = [0, 1, 2, 3, 4, 5, 6];
if ($locale.id == 'en-us') {
$scope.beerForms = {
0: 'no beers',
one: '{} beer',
other: '{} beers'
};
} else {
$scope.beerForms = {
0: 'žiadne pivo',
one: '{} pivo',
few: '{} pivá',
other: '{} pív'
};
}
});
It works all well except if user uses clicks go back history button, the content doesn't change. I've got
$scope.$watch(function () {
return $location.path();
}, function (url) {
//select tab according to url
});
to watch the url change but can't get it work. My logic is when url changes (by go back button) pane should be selected according to the url. Also I think this part
if (panes.length == 2) {
if ($location.path() == "/Pluralization") {
$scope.select(panes[1]);
} else {
$scope.select(panes[0]);
}
}
shouldn't be in addPane()
Anyway, I'm new to Angular and if you think there is a better way to do this please let me know.

Categories

Resources