How to pass data to other scopes variables in angularjs? - angularjs

I have controller
<div ng-controller="LeftSideNavWorkController as vm" ">
<div ng-repeat="item in vm.items track by $index">
<div ng-click="vm.hideAllElements()>Hide</div>
<div ng-show = "showChildren[$index]" >Show/Hide element<div>
</div>
</div>
in controller:
vm.hideAllElements = hideAllElements;
vm.items = [... ... ...]; //some array of items
function hideAllElements() {
//how set all showChildren[] variables to false?
}
the task is that when I click on one it should set all vm.show = false

TRY THIS ONE:
HTML:
<div ng-controller="LeftSideNavWorkController as vm" ">
<div ng-repeat="item in vm.items track by $index">
<div ng-click="vm.hideAllElements()>Hide</div>
<div ng-show = "showChildren[$index]" >Show/Hide element<div>
</div>
</div>
CTRL:
(function() {
'use strict'
angular
.module('myApp')
.controller('appController', appController);
// main.js
function appController($scope, $interval) {
var vm = this;
vm.items = [1, 2, 3, 4, 5];
vm.hideAllElements = hideAllElements;
vm.show = true;
function hideAllElements() {
vm.items.forEach(function(obj, i) {
vm.show = false;
});
}
}
}());

You just have to do
In your view
<div ng-controller="LeftSideNavWorkController as vm" ">
<div ng-repeat="item in vm.items track by $index">
<div ng-click="vm.hideAllElements()>Hide</div>
<div ng-show = "item.show" >Show/Hide element<div>
</div>
</div>
In controller function:
function hideAllElements() {
vm.items.forEach(function(item) {
item.show = false;
}
}

Related

Angular JS: update controller when data change in second controller

what i m doing:
simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.
index.html:
<body ng-controller="myCtrl">
<div id="navbar">
<div class="setToggle">
<input id="slide-sidebar" type="checkbox" role="button" />
<label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
</div>
<div class="setQuestion">
<h2>{{surveys[index].questionTitle}}</h2>
</div>
</div>
<div class="content-wrapper" class="container-fluid">
<div class="sidebar-left">
<div class="first">
<ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
<li class="category">
<a ng-click="expand=!expand">
<span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
{{cat.categoryName}}
</span>
</a>
</li>
<ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
<li ng-show="expand">
<label class="label-style-change">
<input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
<span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
</label>
</li>
</ul>
</ul>
</div>
<div class="second">
<input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
<input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
</div>
</div>
<div class="portfolio">
<div id="main">
<div ng-view></div>
</div>
</div>
</div>
</body>
controller.js
(function() {
var app = angular.module("app.controllers", ["app.service"]);
app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",
function ($scope, $http, $location, $timeout, surveyService, Data) {
surveyService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
$scope.selections = [];
/* create 2d array mannually */
var numInternalArrays = $scope.surveys.length;
for (var i = 0; i < numInternalArrays; i++) {
$scope.selections[i] = [];
};
$scope.index = 0;
var toggleCheckboxFlag = 0;
/* PRIVATE FUNCTION
for find value from selections array and replace it
*/
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
array.splice(index, 1);
toggleCheckboxFlag = 1;
}
});
}
$scope.toggleSelectionCheckbox = function (QuestionId, value) {
toggleCheckboxFlag = 0;
if (!value) return;
findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
if (toggleCheckboxFlag != 1) {
$scope.selections[$scope.index].push({
questionId: QuestionId.questionId,
categoryId: value.subCategoryId,
categoryName: value.subCategoryName,
storeId: 1,
comment: ""
});
}
};
$scope.submitSelection = function() {
$scope.value = $scope.selections[$scope.index];
$scope.hideSubmitButton = true;
$scope.disableCheckbox = true;
$scope.hideEditButton = true;
$location.path("/question/1");
}
});
$scope.EditSelection = function() {
$scope.hideEditButton = false;
$scope.hideSubmitButton = false;
$scope.disableCheckbox = false;
$scope.value = false;
}
$scope.$watch('index', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setIndex(newValue);
});
console.log("controller", Data.getIndex())
}]);
})();
app.js
var app = angular.module('app', ['ngRoute','app.service', 'app.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/question/1', {
templateUrl: 'views/first.html',
controller: 'sidebarCtrl'
})
.when('/question/2', {
templateUrl: 'views/second.html',
controller: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<div id="content-wrapper" ng-show="value">
<div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
<h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
<i class="glyphicon glyphicon-menu-left"></i>
</button>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<form name="myForm">
<div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
<label class="text-center">
<input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
{{item.itemName}}
</label>
</div>
<br/>
<br/>
</form>
</div>
<div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
<i class="glyphicon glyphicon-menu-right"></i>
</button>
<button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
<i class="glyphicon glyphicon-forward"></i>
</button>
</div>
</div>
<div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
<textarea type="text" id="text" class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
</div>
</div>
sidebarCtrl.js
in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.
(function() {
var app = angular.module("app.controllers");
app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {
$scope.inc = 0;
$scope.next = function() {
$scope.inc += 1;
}
$scope.prev = function() {
$scope.inc -= 1;
}
$scope.nextQuestion = function() {
$scope.index += 1;
$location.path("/question/2");
}
$scope.$watch('index', function (newValue, oldValue) {
console.log("SASAS", newValue)
if (newValue !== oldValue) Data.setIndex(newValue);
});
}]);
})();
service.js
(function() {
var app = angular.module("app.service", []);
app.service("surveyService", function($http) {
this.getData = function (callbackFunc) {
$http({
method: "GET",
data: {something: true},
contentType: 'application/json',
dataType: 'jsonp',
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
};
this.setData = function(value) {
if (confirm('Do you wanna to submit?')) {
$http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
window.open("../index.html","_self");
});
} else {
return false;
}
};
});
app.factory('Data', function () {
var data = {
Index: ''
};
return {
getIndex: function () {
return data.Index;
},
setIndex: function (index) {
data.Index = index;
console.log("service", data.Index)
}
};
});
})();
Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,
Try it by test: add any parameter value to myCtrl $scope.name='Bob';
then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.

Linking one controller to another to call service on ng-click

I have two templates with respective controllers and service files. One template's(fleetListTemplate) controller(fleetListController) loads data from its service file(fleetService) and displays in its view(fleetListTemplate).
When this happens, and I click on one of the loaded data from fleetService, I should link fleetListController to fleetSummaryController to get data from its service file (fleetSummaryService) and display in fleetSummaryTemplate view.
Can someone please help me with the coding? Thank you.
The following are the respective modules, templates, controllers and service files.
fleetListModule
"use strict";
angular.module("fleetListModule", []);
fleetListTemplate
<div class="panel1 panel-primary">
<div class="panel-heading" align="center">TRUCKS</div>
<table class="table table-bordered table-condensed table-striped">
<tr>
<th>TruckID</th>
<th>Status</th>
<th>Dest.</th>
<th>Alerts</th>
</tr>
<tr ng-repeat="truck in trucks" ng-click="summaryData()">
<td>{{truck.truckID}}</td>
<td>{{truck.status}}</td>
<td>{{truck.destination}}</td>
<td>{{truck.alerts}}</td>
</tr>
</table>
</div>
fleetListController
"use strict";
angular.module("fleetListModule").controller("fleetListController",
['$scope', 'fleetsService',
function ($scope, fleetsService) {
$scope.trucks = fleetsService.getTrucks();
$scope.summaryData = function () {
$rootScope.$broadcast('obtainSummary');
}
}]);
fleetSummaryModule
"use strict";
angular.module("fleetSummaryModule", []);
fleetSummaryTemplate
<div class="panel2 panel-primary">
<div class="panel-heading">Summary</div>
<table class="table table-bordered table-condensed table-striped">
<tr ng-repeat="summary in truckSummary">
<td>Truck ID: {{summary.truckID}}</td>
<td>Trailer ID: {{summary.trailerID}}</td>
<td>Driver ID: {{summary.driverID}}</td>
<td>Truck Number: {{summary.truckNumber}}</td>
<td>Trailer Number: {{summary.trailerNumber}}</td>
<td>Insurance Due Date: {{summary.insuranceDueDate}}</td>
<td>Maintenance Due Date: {{summary.maintenanceDueDate}}</td>
</tr>
</table>
</div>
fleetSummaryController
"use strict";
angular.module("fleetSummaryModule").controller("fleetSummaryController",
['$scope', 'fleetSummaryService',
function ($scope, fleetSummaryService) {
$scope.$on('obtainSummary', function (event, args) {
$scope.truckSummary = fleetSummaryService.getSummary();
})
}]);
fleetSummaryService
"use strict";
angular.module("fleetSummaryModule").service("fleetSummaryService",
function () {
this.getSummary = function () {
return summary;
};
this.getSummary = function (truckID) {
for (var i = 0, len = truckSummary.length; i < len; i++) {
if (truckSummary[i].truckID === parseInt(truckID)) {
return truckSummary[i];
}
}
return {};
};
var truckSummary = [
{
truckID: 1,
trailerID: '123',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
},
{
truckID: 2,
trailerID: '456',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
},
{
truckID: 3,
trailerID: '789',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
}
];
});
This simple example show to you how to share data between 2 controllers "in one app"
using common service.
angular.module("app", []);
///controller1
angular.module("app").controller("controller1", function ($scope, service) {
$scope.lists = [
{ name: "maher" },
{ name: "Gaurav Ram" },
{ name: "Shaun Scovil" }
];
$scope.send = function () {
service.set("lists", $scope.lists); //set(key, value)
$scope.lists = []; //optional
}
});
///controller2
angular.module("app").controller("controller2", function ($scope, service) {
$scope.lists = [];
//get data from broadcast on the root
service.get("lists"); // get(key)
//set data
$scope.resive = function () {
if (angular.isUndefined($scope.broadcast)) {
$scope.alert = "No data to resive!";
} else {
$scope.alert = null;
$scope.lists = $scope.broadcast;
}
}
});
///service
angular.module("app").service("service", function ($rootScope) {
this.set = function (key, value) {
$rootScope.$broadcast(key, value);
}
this.get = function (key) {
$rootScope.$on(key, function (event, data) {
$rootScope.broadcast = data;
});
}
});
<!doctype html>
<html ng-app="app">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div ng-controller="controller1" class="col-md-6 col-sm-6 col-xs-6">
<div class="page-header">
<h1>controller 1</h1>
</div>
<button ng-click="send()" class="btn btn-primary">Send</button>
<div class="clearfix"></div>
<br/>
<div class="alert alert-info" ng-if="lists.length == 0">Data <b>sent</b> to controller 2, click Resive button to get data</div>
<ul class="list-group">
<li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
</ul>
</div>
<div ng-controller="controller2" class="col-md-6 col-sm-6 col-xs-6">
<div class="page-header">
<h1>controller 2</h1>
</div>
<button ng-click="resive()" class="btn btn-success">Resive</button>
<div class="clearfix"></div>
<br />
<div class="alert alert-info" ng-bind="alert" ng-if="alert"></div>
<ul class="list-group">
<li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>

AngularJS $scope.$parent strange hierarchy

I'm trying to access the $parent in my child controller but for some reason I have to access the Fifth $parent in order to get the actual $scope from the Parent controller, Any Ideas?
Parent Controller
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user',
function($scope, $rootScope, user) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = []
$scope.selectedCompanyIndex = undefined;
$scope.selectedCompany = undefined;
$scope.selectedTicketIndex = undefined;
$scope.selectedTicket = undefined;
}]);
Child Controller
angular.module('App')
.controller('HomeCompaniesTabController', ['$scope', 'Companies',
function($scope, Companies) {
$scope.loadCompanies = function () {
$scope.companies = Companies.query();
}
/**
* Init
*/
$scope.selectCompany = function (company, index) {
$scope.$parent.selectedCompanyIndex = index; //this doesnt work
$scope.$parent.$parent.$parent.$parent.$parent.selectedCompany = company; //this does, why?
console.log($scope);
}
if($scope.currentUser.security < 3) {
$scope.loadCompanies();
}
}]);
Home template
<div ng-include="'dist/templates/header.html'"></div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
company : {{selectedCompany}}
</div>
</div>
<tabset>
<tab ng-repeat="tab in tabs" heading="{{tab.heading}}">
<div ng-include="'dist/templates/' + tab.template" ></div>
</tab>
</tabset>
</div>
Child template
<div class="row-fluid" ng-controller="HomeCompaniesTabController">
<div class="col-md-3">
<h4>Lista de Empresas</h4>
<hr/>
<div class="list-group">
<a
href=""
class="list-group-item"
ng-repeat="company in companies"
ng-click="selectCompany(company, $index)">
<h4 class="list-group-item-heading">
{{company.name}}
</h4>
</a>
</div>
</div>
<div class="col-xs-9">
<div ng-show="selectedCompany">
<h4><b>{{selectedCompany.name}}</b></h4>
</div>
</div>
Based on the comments of charlietfl I came up with this simple service for sharing data
angular.module('App')
.factory('SharedData', [function () {
return {
}
}]);
Then I simply inject it in the controllers
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user', 'SharedData',
function($scope, $rootScope, user, SharedData) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.sharedData = SharedData;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = [];
}]);

Error "cannot set property gridDim of undefined" in angular js

Getting error "cannot set property gridDim of undefined" while using ng-grid in angular js. i have already declared vm.gridOptions = { data: 'vm.course_view'};.plz help me
<section class="mainbar">
<section class="matter">
<div class="container">
<div class="row" ng-controller="Course_view">
<div class="col-lg-5 col-lg-offset-2">
<div class="widget wblue">
<div vis-widget-header title="{{vm.title}}"></div>
<div class="widget-content user">
<!-- <table data-toggle="table" data-height="150" class="table table-condensed table-hover">
<thead>
<tr>
<th>Lesson</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in vm.course_view"
>
<td>{{c.firstName}}</td>
</tr>
</tbody>
</table> -->
<div class="gridStyle" ng-grid="course_view"></div>
</div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</section>
Here is Code for controller
(function() {
'use strict';
angular
.module('app.course_view')
.controller('Course_view', Course_view);
/* #ngInject */
function Course_view($state, dataservice, logger) {
var vm = this;
vm.course_view = [];
vm.title = 'Course_view';
vm.gridOptions = { data: 'vm.course_view', columnDefs: [
{field:'firstName', displayName:'firstName'}
]};
activate();
function activate() {
return getCourse_View().then(function() {
logger.info('Activated course_view View');
});
}
function getCourse_View() {
return dataservice.getCourse_View().then(function(data) {
vm.course_view = data;
debugger;
return vm.course_view;
});
}
}
})();
Please, try to change the following code:
<div class="row" ng-controller="Course_view">
on
<div class="row" ng-controller="Course_view as courseCtrl">
and
<div class="gridStyle" ng-grid="course_view"></div>
on
<div class="gridStyle" ng-grid="courseCtrl.course_view"></div>
And please, give me feedback about your success/fail in comments.
UPDATE:
I've created JSFiddle for you with working example.
I'm a little bit simplified example, but it should work.
<div ng-controller="CourseViewCtrl as ctrl">
<div class="gridStyle" ng-grid="ctrl.gridOptions"></div>
</div>
(function() {
'use strict';
var myApp = angular.module('myApp',['ngGrid']);
myApp.controller('CourseViewCtrl', CourseViewCtrl);
function CourseViewCtrl($http) {
var vm = this;
vm.course_view = [];
vm.gridOptions = {
data: 'ctrl.course_view'
};
activate();
function activate() {
return $http.get("/data").success(function(data) {
vm.course_view = data;
});
};
}
})();
I want to note on main differences between your code:
Grid options in the controller:
vm.course_view = [];
vm.gridOptions = {
data: 'ctrl.course_view'
};
Grid on the view:
<div class="gridStyle" ng-grid="ctrl.gridOptions"></div>

Why won't my view template bind to a scope variable with AngularJS?

My view is:
<div class="container" ng-controller="MyController">
<div class="row">
<div class="col-md-8">
<textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
</div>
<div class="col-md-4" ng-show="sourceLanguage !== null">
Language: {{ sourceLanguage }}
</div>
</div>
</div>
My controller is:
webApp.controller('MyController', [
'$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
$scope.init = function() {
return $scope.sourceLanguage = null;
};
$scope.parseLanguage = function() {
return TranslateService.detectLanguage($scope.myWords).then(function(response) {
console.log($scope.sourceLanguage);
$scope.sourceLanguage = response.data.sourceLanguage;
return console.log($scope.sourceLanguage);
});
};
return $scope.init();
}
]);
The console logs show the right data. But in the view, sourceLanguage never updates. Why would this be?
In case the promise you are evaluating is not part of the Angular context you need to use $scope.$apply:
$scope.parseLanguage = function() {
TranslateService.detectLanguage($scope.myWords).then(function(response) {
$scope.$apply(function() {
$scope.sourceLanguage = response.data.sourceLanguage;
});
});
};

Resources