AngularJs - How to use method of one controller in multiple controllers? - angularjs

I am bit new to AngularJS.
Here is my code:
table.js
.controller('ModalDemoCtrl', function ($scope, $rootScope, $uibModal, $log, tableService) {
$rootScope.$on("openRootDialog", function(event, html){
$scope.openDialog(html);
});
$scope.openDialog = function (html) {
// TODO: replace option dialog with your options:
var modalInstance = $uibModal.open({
animation: true,
templateUrl: html + '.html',
controller: 'ModalInstanceCtrl',
size: 'md',
backdrop: 'static',
keyboard: true,
resolve: {
content: function () {
return $scope.modalContent;
}
}
});
modalInstance.result.then(function (result) {
// Add user in you database
tableService.addUserData(result);
// Add user in your view
$scope.data.push(result)
$scope.tableEdit.reload();
});
}
})
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, content) {
$scope.modalContent = content;
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
})
//user
.controller('tableUserCtrl', function($scope, $rootScope, $uibModal, $log, $filter, $sce, ngTableParams, tableService) {
//var data = tableService.data;
var selfUser = this;
$scope.data = [];
//selfUser.obj = null;
var promise = tableService.getUserData();
promise.then(
function(payload) {
$scope.data = payload.data;
$scope.tableEdit = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: $scope.data.length, // length of data
getData: function($defer, params) {
//$defer.resolve(selfUser.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
//sorting
var orderedData = params.sorting() ? $filter('orderBy')($scope.data, params.orderBy()) : $scope.data;
//filtering
orderedData = params.filter() ? $filter('filter')(orderedData, params.filter()) : orderedData;
//orderedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
//params.total(orderedData.length);
//$defer.resolve(orderedData);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
},
function(errorPayload) {
$log.error('failure loading movie', errorPayload);
});
//to update data
$scope.updateUser = function(w) {
tableService.updateUserData(w);
}
$scope.removeUser = function(id, w) {
tableService.removeUserData(id)
//alert(JSON.stringify($scope.data))
$scope.data.splice($scope.data.indexOf(w), 1);
$scope.tableEdit.reload();
//alert(JSON.stringify($scope.data))
}
$scope.openUserDialog = function(html) {
$rootScope.$emit("openRootDialog", {});
}
})
view.html
<div class="container" data-ng-controller="tableUserCtrl">
<!--<div class="p-t-0" data-ng-controller="ModalDemoCtrl"> -->
<script type="text/ng-template" id="adduser.html">
<div class="modal-header">
<!--<h4 class="modal-title">Add User</h4>-->
</div>
<form role="form" ng-submit="insertInfo(userInfo);" name="userForm" novalidate>
<div class="modal-body m-l-15">
<div class="row">
<div class="form-group fg-float m-b-30">
<div class="fg-line">
<input type="text" class="input-sm form-control fg-input" name="name" ng-model="user.name" required="">
<label class="fg-label">Name</label>
</div>
<div ng-show="userForm.$submitted || userForm.name.$touched">
<div ng-show="userForm.name.$error.required" class="error">This field is required.</div>
</div>
</div>
...
</div>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="ok(user);" ng-disabled="userForm.$invalid">Submit</button>
<button class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</form>
</script>
<button class="btn btn-default pull-right" ng-click="openUserDialog('adduser')">Add User</button><br/><br/>
<!--</div>-->
<div class="card">
<div class="card-header">
<h2>Users <small></small></h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table ng-table="tableEdit" class="table table-striped table-vmiddle" show-filter="true">
<tr ng-repeat="w in $data" ng-class="{ 'active': w.$edit }">
<td data-title="'Name'" filter="{ 'name': 'text' }" sortable="'name'">
<span ng-if="!w.$edit">{{ w.name }}</span>
<div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.name" /></div>
</td>
...
<td data-title="'Actions'">
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = true"><i class="zmdi zmdi-edit"></i></button>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="removeUser(w.user_id, w)"><i class="zmdi zmdi-close"></i></button>
<button type="button" class="btn btn-success" ng-if="w.$edit" ng-click="w.$edit = false; updateUser(w)"><i class="zmdi zmdi-check"></i></button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
I am passing html template name in openUserDialog function from view as I need to use that name in openDialog function written in ModalDemoCtrl so I can use dynamic templates in modal.
I have searched a lot but couldn't get exact things that how can I pass args to openRootDialog from openUserDialogfunction written in tableUserCtrl?
can anyone please help me? is there any syntax issue? I don't have any idea about $emit, $on etc. as am using it first time.

Use $rootscope,
this is example:
app.run(function($rootScope) {
$rootScope.someMethod=function(){
//do staff
}
}
in another controller just use $scope.someMethod(), in view someMethod().
it is global method now.

Related

Laravel - pass form input from angular to API controller?

I have a delete controller in my backend that is done in angular. Its angular controller looks like this:
angular.module('dashboard')
.controller('CoursesDeleteController', ['$scope', '$http', '$location', '$routeParams', function ($scope, $http, $location, $routeParams) {
$scope.id = $routeParams.id;
$scope.courses = {
delete: 0
};
$scope.loaded = false;
$scope.busy = false;
$scope.error = false;
$scope.setDelete = function (value) {
$scope.webinarcourses.delete = value;
};
$scope.delete = function () {
$scope.busy = true;
$http.delete('/api/courses/' + $scope.courses.id, $scope.courses).then(function (response) {
$scope.busy = false;
$location.path('/courses');
}, function (response) {
$scope.busy = false;
$scope.error = 'Unable to delete course...';
});
};
var load = function () {
$scope.busy = true;
$http.get('/api/courses/' + $scope.id).then(function (response) {
$scope.courses = response.data;
$scope.busy = false;
$scope.loaded = true;
}, function () {
$scope.busy = false;
$scope.error = 'Unable to load course...';
});
};
load();
}]);
The view is
<form role="form" class="panel-footer">
<div class="form-group col-xs-12 col-sm-6 col-md-2">
<label>Delete from Integrations?</label><br>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-info"
ng-class="{ active: courses.delete == 1 }"
ng-click="setDelete(1)">
<input type="radio"> Yes
</label>
<label class="btn btn-info"
ng-class="{ active: courses.delete == 0 }"
ng-click="setDelete(0)">
<input type="radio"> No
</label>
</div>
</div>
<button class="btn btn-danger" ng-click="delete()" ng-disabled="busy || !loaded"><span class="glyphicon glyphicon-trash"></span> Delete</button>
<span class="glyphicon glyphicon-arrow-left"></span> Back
<div class="progress progress-striped active push-sm" ng-show="busy">
<div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
<span class="sr-only">Busy...</span>
</div>
</div>
</form>
Then in my API controller:
public function destroy($id)
{
$data=Input::all(); // do something with this data...
\App\Courses::find($id)->delete();
}
The problem is I am not seeing any data. I thought I would have courses.delete available via Input:: but it is null.
I must be overlooking something and maybe it has to do with the fact that the Courses model does not have a delete column, but I thought it wouldn't matter if I am just passing from angular to the API controller and not actually trying to access a non existent column. I am just trying to use courses.delete as a way to determine some actions in the delete method of the API controller.
Ok, I overlooked the peculiarities of the delete method. Turns out I just needed to do do this:
$http.delete('/api/courses/' + $scope.courses.id, {
params: {delete: $scope.courses.delete}
}).then(function (response) {
regards

ion-slides, each overlap with ng-repeat

I'm real newbie in ionic, html, angular and java script. I have an app that take some JSON data and display it with ng-repeat.
But when I tried to switch to the next slide, it overlap. and I have an $interval that refresh JSON each 5 sec, it reset to the first slide also.
here html:
<ion-view title="home">
<ion-content ng-controller="temperatureCtrl">
<div ng-init="init()"></div>
<ion-slides options="options" slider="data.slider" >
<ion-slide-page ng-repeat="channel in channels">
<div class="list">
<h2><center>canal# {{channel.canal}}</center></h2>
<br/>
<center>
<button class="button button-stable" ng-click="switchChannel(channel, channel.canal)" ng-model="channel.status">
{{channel.status}}
</button>
</center>
<div class="list">
<label class="item item-input">
<input type="text" style="text-align:center;" placeholder="Channel name" ng-model="channel.name" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
</label>
</div>
<h4><center>
<span class="Ainput" ><h3>{{channel.temperature}}ºC</h3></span>
</center></h4>
<h3><center>Setpoint= {{channel.setPoint}}</center></h3><br>
<div class="item range range-positive">
<i class="icon ion-minus-round"></i>
<input type="range" name="setpoint" min="5" max="30" step="0.5" value="33" ng-model="channel.setPoint" ng-focus="stopRefresh()" ng-blur="restartRefresh()">
<i class="icon ion-plus-round"></i>
</div>
<centrer>
<button class="button button-dark button-block padding " ng-click="channelsClk(channel, channel.setPoint)">ok</button>
</centrer>
<h3>
<span class="permRun">{{channel.permission}}</span>
</h3>
<h3>
<span class="AoutputChannel">{{channel.percentOut}}%</span>
</h3>
</ion-slide-page>
</ion-slides>
</ion-content>
and the controler:
main.controller("temperatureCtrl", ["$scope", "$interval", "ArduinoService", function($scope, $interval, service) {
var autoRefresh;
$scope.channels = [];
$scope.options = {
loop: false,
effect: 'fade',
speed: 500,
}
$scope.data = {};
$scope.$watch('data.slider', function(nv, ov) {
$scope.slider = $scope.data.slider;
})
function startRefresh(){
autoRefresh = $interval(function() {
updateAjax();
}, 5000);
}
function updateAjax() {
service.getChannels(function(err, result) {//get json data
if (err) {
return alert(err);
}
// puis les mets dans le scope
$scope.channels = result.channels;
})
};
$scope.init = function() { //on load page first get data
updateAjax();
startRefresh()
}
$scope.switchChannel = function($scope, channel) { // change name function
var switchCh = {canal : $scope.canal, status : $scope.status}
service.switchChannel(switchCh, function() {
});
updateAjax();
};
$scope.channelsClk = function($scope, channel) {
var chanObj = {setPoint : $scope.setPoint, name : $scope.name, canal : $scope.canal
};
service.putChannels(chanObj, function() {
});
}
$scope.stopRefresh = function() { //ng-mousedown
$interval.cancel(autoRefresh);
};
$scope.restartRefresh = function() {
startRefresh();
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopRefresh();
});
}]);
remove option fade solve the problem.
$scope.options = {
loop: false,
//effect: 'fade', /* <-- */
speed: 500,
}

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.

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Bind values to UI Bootstrap Modal

I have a table with a view button, when view is clicked modal display but now I want to display certain data on the modal. I am using .html pages.
I am not sure what am I missing here
html
<td>
<span>
<input class="btn btn-sm btn-dark" data-ng-click="launch('create',client)" type="button" value="view" />
</span>
</td>
This will luanch the modal
Modal
<div class="modal fade in" ng-controller="dialogServiceTest">
<div class="modal ng-scope">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<span class="glyphicon glyphicon-star"></span> Client Details
</h4>
</div><div class="modal-body">
<ng-form name="nameDialog" novalidate="" role="form" class="ng-pristine ng-invalid ng-invalid-required">
<div class="form-group input-group-lg" ng-class="{true: 'has-error'}[nameDialog.username.$dirty && nameDialog.username.$invalid]">
<label class="control-label" for="username">Name:</label>
<input type="text" name="username" id="username" ng-model="client.ClientName" ng-keyup="hitEnter($event)" required="">
<span class="help-block">Enter your full name, first & last.</span>
</div>
<div>{{client.ClientName}}</div>
</ng-form>
</div><div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
<button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="(nameDialog.$dirty && nameDialog.$invalid) || nameDialog.$pristine" disabled="disabled">Save</button>
</div>
</div>
</div>
</div>
Angular
angular.module('modalTest', ['ngRoute','ui.bootstrap', 'dialogs'])
.controller('dialogServiceTest', function ($scope,$http, $rootScope, $timeout, $dialogs) {
$scope.clients = []; //Array of client objetcs
$scope.client = {}; //Single client object
$scope.launch = function (which,client) {
var dlg = null;
alert(client.ClientName);
dlg = $dialogs.create('/templates/Modal.html', 'whatsYourNameCtrl', {}, { key: false, back: 'static' });
dlg.result.then(function () {
$scope.client.ClientName = client.ClientName;
});
})
.run(['$templateCache', function ($templateCache) {
$templateCache.put('/templates/Modal.html');
}]);
here is some of my code
$scope.showScreenSizePicker = function(){
$scope.actionmsg = "";
var modalWindow = $modal.open({
templateUrl: '{{url()}}/modals/modalScreenSizePicker',
controller: 'modalScreenSizePickerController',
resolve: {
titletext: function() {return "Screen Sizes: ";},
oktext: function() {return "Close";},
canceltext: function() {return "Cancel";},
labeltext: function() {return "";},
}});
modalWindow.result.then(function(returnParams) {
$scope.setViewSize(returnParams[0], returnParams[1]);
});
}
you can see i am passing variables into modal using resolve. If you want to pass values back from the modal you can grab the variable returnParms (array)
and here is my controller code:
angular.module('myWebApp').controller('modalScreenSizePickerController', function($scope, $modalInstance, titletext, labeltext, oktext, canceltext) {
$scope.titletext = titletext;
$scope.labeltext = labeltext;
$scope.oktext = oktext;
$scope.canceltext = canceltext;
$scope.customHeight = 800;
$scope.customWidth = 600;
$scope.selectCustomSize = function(width, height){
if (width < 100){ width = 100; }
if (height < 100){ height = 100; }
$scope.selectItem(width, height);
}
$scope.selectItem = function(width, height) {
var returnParams = [width, height];
$modalInstance.close(returnParams);
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
});
hope my sample helps
I think what you are looking for is the resolve property you can use with the $modal service. I am not exactly sure which version of UI Bootstrap you are using, but the latest one works as follows:
var myModal = $modal.open({
templateUrl: '/some/view.html',
controller: 'SomeModalCtrl',
resolve: {
myInjectedObject: function() { return someObject; }
});
myModal.result.then(function(){
// closed
}, function(){
// dismissed
});
Then you can use the injected resolved value inside the modals controller:
app.controller('SomeModalCtrl', function ($scope, $modalInstance, myInjectedObject) {
// use myInjectedObject however you like, eg:
$scope.data = myInjectedObject;
});
You can acces the client in modal by using "$scope.$parent.client" - "$parent" give you $scope from witch the modal was open with all data.

Resources