This is my partial view settings.html
<div ng-controller="settingsController">
<h3>General Settings</h3>
<table class="table">
<tbody>
<tr class="success">
<td class = "col-xs-3">Language:</td>
<td class = "col-xs-9">Gmail display language:
<select ng-model = "userPreferences.selectedLang" ng-options="language for language in languages">
<option value = ""> Choose a language </option>
</select>
</td>
</tr>
<tr class="danger">
<td class = "col-xs-3">Conversation View</td>
<td class = "col-xs-9">
<input type = "radio" name = "conversation" id = "converseOn" ng-model="userPreferences.converse.state" value = "on" checked>
<label for="converseOn"> Conversation view on </label>
<aside>
<input type = "radio" name = "conversation" ng-model="userPreferences.converse.status" value = "off" id = "converseOff">
<label for="converseOff"> Conversation view off </label>
</aside>
</tr>
<tr class="info">
<td class = "col-xs-3">Maximum page size: </td>
<td class = "col-xs-9"> Show conversations per page
<select ng-model = "userPreferences.selectedNumber" ng-options="conversation for conversation in conversations">
<option value = ""> Choose the no.of conversations to display </option>
</select>
<aside id = "pageSize" > Show contacts per page
<select ng-model = "selectedNumberContacts" ng-options="contact for contact in contacts">
<option value = ""> Choose the no.of contacts to display </option>
</select>
</aside>
</td>
</tr>
</tr>
</tbody>
</table>
<div class="form-actions" >
<button type="submit" class="btn btn-primary" ng-click = "setPreference()">Save changes</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
This is the settingsController.js
(function() {
'use strict';
var settingController = function (fetchDataService, $scope, savePreferenceService) {
var url = 'app/mock/settings.json';
fetchDataService.getContent(url)
.then(function(response){
$scope.contacts = response.data.contacts;
$scope.languages = response.data.languages;
$scope.conversations = response.data.conversations;
$scope.undoSend = response.data.undoSend;
});
$scope.userPreferences = {
selectedLang : '',
converse : {
state: 'on'
},
selectedNumber : 0
}
$scope.setPreference = function () {
savePreferenceService.selectedPreferences($scope.userPreferences.selectedLang, $scope.userPreferences.converse.state, $scope.userPreferences.selectedNumber);
}
};
angular.module('iisEmail')
.controller ('settingsController',
['fetchDataService', '$scope', 'savePreferenceService', settingController]);
}());
This is the savePreferenceService.js
(function() {
'use strict';
var savePreferenceService = function () {
this.selectedPreferences = function (selectedLang, converse, selectedNumber) {
this.selectedLang = selectedLang;
this.converse = converse;
this.selectedNumber = selectedNumber;
console.log(this.selectedLang);
console.log(this.converse);
console.log(this.selectedNumber);
}
};
angular.module('iisEmail')
.service ('savePreferenceService', savePreferenceService);
}());
So, basically my goal is to save user preferences when the Save changes button is clicked.
To achieve this functionality, I have defined an object in the controller, and binded its properties to the view using ng-model. When the save changes button is clicked, the setPreference() function is called which makes a service savePreferenceService call. The savePreferenceService saves options chosen by the user. Everything works as expected.
I just want to know if there is a better way of doing this (in terms of best practices). My requirement is to save the options chosen by a user in a service.
I'm not really seeing how data could possibly be saved when you do something like a page refresh, unless you're not showing the code here?
If you want to preserve data saves whenever the user visits your page, you can always use localstorage, which stores info in the user's browser. There are various web tutorials on how to utilize localstore, but this website (which didn't take long to find), includes and extends localstorage as a service, and to use that service as a way to store data in there.
http://learn.ionicframework.com/formulas/localstorage/
(code below is taken from this link)
angular.module('ionic.utils', [])
.factory('$localstorage', ['$window', function($window) {
return {
set: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
setObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key) {
return JSON.parse($window.localStorage[key] || '{}');
}
}}]);
and to use this service:
angular.module('app', ['ionic', 'ionic.utils'])
.run(function($localstorage) {
$localstorage.set('name', 'Max');
console.log($localstorage.get('name'));
$localstorage.setObject('post', {
name: 'Thoughts',
text: 'Today was a good day'
});
var post = $localstorage.getObject('post');
console.log(post);
});
Or you could just use localstorage the old fashion way using plain old javascript..
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Sounds like what you have is working for you. Not sure exactly what you mean by 'I just want to know if there is a better way of doing this' since that is pretty subjective.
What I do notice right away is that the current implementation makes your user preferences session based because they are only retained in-memory, meaning that if the user uses the app, makes changes to the preferences, leaves the app and returns, the changes are lost. If you need to preserve them, then I would suggest using LocalStorage or actually storing them in some type of data store (file, database, ...).
Also, I would suggest making your service the owner of the preferences data instead of splitting the responsibility between the controller and the service. What I mean by that is that the default preferences are owned by the controller, but only when updated do they make it to the service. What I would do instead is
change the service to have a get method and a set method. Perhaps getPreferences() and setPreferences(...).
change the controller to call the getPreferences method instead of assigning a static preferences object
call the setPreferences method from the controller's setPreference method
Related
Purpose
I am trying to get admin and customer show in different stages, admin can post the data after clicking the toggleShowDiv(), which allows customer to see the data.
Question
How to pass !isAdmin() into ng-if? Currently, I am only getting isAdmin as default.
Is able to post it into table TD by TD (row by row)? not sure, I am writing the correct code here.
My thought
Can I use ng-if to each single TD = isAdmin() or !isAdmin, and control by a click function?
$scope.showDiv = isAdmin();
$scope.toggleShowDiv = function (auction) {
var title = 'text.......';
var text = 'are you sure?';
ConfirmModal(title, text, function () {
$scope.showDiv = !isAdmin() ;
});
};
HTML
<div ng-if="showDiv">
<tbody class="auction-group" ng-repeat="a in foos">
<td ng-if="isAdmin()">
<input type="checkbox" ng-click="toggleShowDiv()" />
</td>
</div>
Update
isAdmin() is just a function that passed from the backend.
function isAdmin() {
return !!($aScope.currentUser && $aScope.currentUser.isAdministrator);
}
Please note: the question is not about the isAdmin() function, it works fine. What I want to do is to use a click function to show and hide the table row.
Have a look at this. Here you have 2 users online at the same time, dude1 (admin) and dude2 (non admin). You can toggle the display from the admin side for the non admin side by having a call to the back end that continuously checks if the display is valid or not. For putting a toggle on the table rows you need to just add the ng-if to the <tr> elements.
var app = angular.module('app', []);
app.controller("controller", function($scope) {
$scope.dude1 = {admin: true, name: [{name: 'A+', country:'India', publish: true}, {name: 'A', country:'Unknown', publish: true}]};
$scope.dude2 = {admin: false, name: [{name: 'A+', country:'India', publish: true}, {name: 'A', country:'Unknown', publish: true}]};
$scope.toggler = (index) => {
$scope.dude1.name[index].publish = !$scope.dude1.name[index].publish;
};
$scope.names = (dude) => {
return dude.name;
};
setInterval(() => {
/**
* Any backed function to get and repopulate the data.
* Update the value of publish from the server. I'm just using
* the other guys data. But you should fetch it from the server.
*/
$scope.dude2 = valfromServer();
// console.log($scope.dude2, $scope.dude1);
}, 2000);
var valfromServer = () => {
return {
admin: false,
name: $scope.dude1.name
};
};
$scope.publish = (dude, index) => {
return dude.admin || dude.name[index].publish;
};
$scope.isAdmin = (dude) => {
return dude.admin;
};
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
</head>
<body ng-app="app" ng-controller="controller">
<span>Admin Panel</span>
<div>
<table style="width:40%">
<tr ng-repeat="x in names(dude1)" ng-if="publish(dude1, $index)">
<td>{{ x.name }}</td>
<td>{{ x.country }}</td>
<td>{{ $index }}</td>
<td><button ng-click="toggler($index)" ng-if="isAdmin(dude1)">Publish</button></td>
</tr>
</table>
</div>
<hr>
<span>Non admin panel</span>
<div>
<table style="width:40%">
<tr ng-repeat="x in names(dude2)" ng-if="publish(dude2, $index)">
<td>{{ x.name }}</td>
<td>{{ x.country }}</td>
<td>{{ $index }}</td>
<td><button ng-click="toggler($index)" ng-if="isAdmin(dude2)">Publish</button></td>
</tr>
</table>
</div>
</body>
</html>
<div ng-if="showDiv == true || isAdmin == true">
<tbody class="auction-group" ng-repeat="a in foos">
<td ng-if="isAdmin == true">
<input type="checkbox" ng-click="toggleShowDiv()" />
</td>
</div>
JS code Let say first any one who enters will be customer
$scope.showDiv = false;
$scope.isAdmin = false;
now when response comes form backend check the response and change the value of $scope.isAdmin accordingly.
if(response == admin){
$scope.isAdmin= true;
}else{
$scope.isAdmin = false;
}
now in onclick checkbox function
$scope.toggleShowDiv = function (auction) {
var title = 'text.......';
var text = 'are you sure?';
ConfirmModal(title, text, function () {
if($scope.showDiv == false){
$scope.showDiv = true;
}else{
$scope.showDiv = false;
}
});
};
Well I think that you should use some var that change according if the user click like $scope.showTable = true /false. But not complety sure about your real need.
I am confused on your question -
I will suggest few points, i hope it will help you -
ng-if is a inbuilt directive. You can use it on any DOM element. You can control it by using attribute or function, only need to pass Boolean attribute to this directive. Eg:
ng-if="showHideAttribute" or ng-if="functionNameWhichReturnBoolean()"
Scope - if you are clicking on button/checkbox/ng-click applied element is available in the same scope of applied ng-if directive then no problem. Otherwise you need to use service or observers (on/emit/broadcast) or rootScope then only it will work.
I hope you are receiving isAdmin = true/false from backend in your function. So, i am thinking this is the problem of scope.
Instead of ng-if="showDiv" use something link ng-if="obj.showDiv"
In the controller define $scope.obj = {};
The issue is ng-if creates its own scope, so always pass data as an object because objects in JS are passed by reference.
You can do this
ng-if = "isAdmin == false"
You're really confusing me, but if I understood correctly, it is something like this you want?
First things first, your HTML is truely horrible, parts of tables in divs? Don't do that...
Secondly, don't hack kabout with the isAdmin to toggle things.
isAdmin should only be used to check if a user is an admin.
You can however create another variable that instantiates to the same value, and use that one to toggle stuff.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
this.content = 'This is some unpublished content, only the admin can view, unless you\'ve now gone and publish it.';
this.isPublished = false;
this.isAdmin = false;
});
/* Put your css in here */
textarea,
label,
button {
display: block;
margin: 15px 15px 0 0;
}
button {
display: inline-block;
}
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl as $ctrl" ng-init="$ctrl.isAdmin=false">
<article>
<section class="content">
<section ng-if="$ctrl.isAdmin || $ctrl.isPublished">{{ $ctrl.content }}</section>
<section ng-if="!$ctrl.isAdmin && !$ctrl.isPublished"><pre>-- no published content found --</pre></section>
</section>
<section class="admin-only" ng-if="$ctrl.isAdmin">
<label><input type="checkbox" ng-model="$ctrl.isPublished"> publish article</label>
</section>
</article>
<hr />
<label><input type="checkbox" ng-model="$ctrl.isAdmin"> is admin</label>
</div>
</div>
edit:
You're still confusing me, but does this come closer to what you want / need?
What i understand is, "When admin trigger some action i.e. ng-click, user should be able to see that data/changes."
If this is the case, consider following:
I'm damn sure that this is not going to happen on the same machine.
Admin will be using the application on his machine from where it'll
do some action i.e. ng-click will gets fired and some data will gets
changed on server.
Now there will be (n) number of users using the application from
their machines. How they will get to know about the change which admin has made?
In such scenario, when there is changes on server and
client(browser) should be aware of that we make use of socket.io,
which listens to events from server and refreshes itself when there
is some changes on server state or we can say, when admin has
triggered some action i.e. ng-click.
Let me know, if you have any queries.
Thanks
I have an angular service that fetch contacts data from the database, I then use these data so that the user can add one contact or more to a deal, so there is a many to many relationship between the deal and contact, the selected data are displayed in a grid (syncfusion grid).
I need to have a constant list of the data retrieved from database, and a varible containing the selected contacts that I pass to the syncfusion grid, when the user add from the dropdown I add this contact to the grid and remove it from the dropdown list, and if I deleted it from the grid I return it back to the drop down list, so here's my code:
this service get the contact list:
var contactsListDB = [];
contactService.getAll().then(function (contacts) {
contactsListDB = contacts.data;
$scope.contactsList = contactsListDB; // the scope used in the select input in the HTML
});
the method that add contact:
$scope.addContact = function (contact) {
var contactJson = JSON.parse(contact);
$scope.dealContacts.push(contactJson);
var index = $scope.contactsList.findIndex(x => x.id == contactJson.id);
SyncFusionDealContact($scope.dealContacts);
$scope.contactsList.splice(index, 1);
}
this function is invoked in HTML:
<ng-form name="ContactForm">
<md-input-container>
<label>{{"Contact" | translate}}</label>
<md-select ng-model="contact">
<md-option value="{{null}}">-- {{"selectContact" | translate}} --</md-option>
<md-option ng-repeat="contact in contactsList" value="{{contact}}">{{contact.name}}</md-option>
</md-select>
</md-input-container>
<md-input-container>
<div>
<button class="btn btn-primary" type="submit" ng-disabled="!ContactForm.$valid" ng-click="addContact(contact)" aria-label="submit">{{'add' | translate}}</button>
</div>
</md-input-container>
<div id="GridDealContacts">
<script id="columnTemplateContacts" type="text/x-jsrender">
<a class="btn btn-danger btn-xs contactDelete" data-id="{{:id}}" ng-click="DeleteContact{{:id}}"><i class="fa fa-trash-o "></i></a>
<!--add delete button-->
</script>
</div>
</ng-form>
When the page is loaded I check if the object is being edited and then I exclude the existing contacts from the list comming from contacts table:
$scope.dealContacts = deal.contacts;
SyncFusionDealContact($scope.dealContacts);
execludeContacts()
execludeContacts function:
function execludeContacts() {
var exIds = [];
if ($scope.dealContacts.length > 0) {
exIds = $scope.dealContacts.map(x=> x.id)
}
var conts = contactsListDB;
conts.forEach(function (item, index) {
if (exIds.includes(item.id)) {
conts.splice(index, 1);
}
})
$scope.contactsList = conts;
}
this function handles delete action:
$scope.DeleteContact = function (id, index) {
if (id <= 0) {
$scope.dealContacts.splice(index, 1)
SyncFusionDealContact($scope.dealContacts);
}
else {
if (confirm("Are You Sure?")) {
dealService.deleteContact(id, $routeParams.id).then(function (success) {
if (success.data.isSuccess) {
SyncFusionDealContact($scope.dealContacts);
var one = contactsListDB.filter(x => x.id == id)[0];
$scope.contactsList.push(one);
$scope.dealContacts.splice(index, 1);
}
else {
alert('Cannot delete');
}
SyncFusionDealContact($scope.dealContacts);
});
}
}
}
In the code above I tried to save a copy of the contacts list in a variable that can't be changed contactsListDB, so that when a record is deleted from the grid I can get it back from this array to add it in the drop-down list again, but what happens is that the array is changed:
Screenshot:
I'm not sure of what you're asking, but I think you want to 'save' the data somewhere? If that's the case, take a look at using a factory or service. I prefer using a factory because of its simplicity.
From the short period I've worked with Angular, I know that a factory will always stay alive (even while switching views in SPA) until you refresh the page.
In a simple example, the factory will hold a list of the contacts, and have several functions like your addContact and deleteContact. This makes your code less cluttered and you just have to call the factory and its functions in your code.
I currently can't give a specific example (as I prefer using my own factories and its usage), but here you can find a comparison between factory and service and how to use them.
If I misunderstood your question, please do tell. :D
I have a table with an edit and delete button. But now I also want to make a clone button.
The clone button should work as follows: It clones almost all the data (data such as the id he cannot take) from the row that the user has clicked. Then it goes to the edit page and there it fills the data in the input/select values.
But I have no idea how I get this done.
I have now a function which output all the data: var cloneJob = angular.extend(job);
Then it goes to the edit page location.href = '#/jobs/add';
But the problem is that he doesn't fill the input/select values.
Does AngularJS has a function for this? And am I on the right track or do I need to do something else?
UPDATE
Here is a litle bit more code:
This is my the code of my table:
<tr ng-repeat="job in (filtered.rows = (jobs | orderBy: orderByDate:true | filter:filterByActive | filter:filter.query)) | skip:pagination.pageSkip() |limitTo:pagination.perPage" ng-class="{ inactive : !job.active }" style="cursor: pointer;">
<td>
<span ng-bind="job.title"></span>
</td>
<td>
<span ng-bind="job.client.name"></span>
</td>
<td>
<span ng-bind="job.referenceNumber"><span>
</td>
<td>
<span ng-bind="job.creationDate"><span>
</td>
<td>
<a ng-href="#/jobs/edit/{{job.id}}/tab/candidates" ng-bind="job.candidates.length"></a>
</td>
<td>
<span class="status" ng-class="job.status.value"></span>
</td>
<td>
<a ng-if="job.active" ng-href="#/jobs/edit/{{job.id}}" class="icon go">
<span class="tooltip" translate="job_name_details"></span>
</a>
<a ng-if="job.active" class="icon close" ng-click="showClosePopup(job)">
<span class="tooltip" translate="job_close"></span>
</a>
<a ng-click="cloneJob(job)" ><span>Clone!</span></a>
<!-- <button data-ng-click="cloneItem(food)" class="btn inline">Add</button> -->
</td>
</tr>
Function cloneJob is:
$scope.cloneJob = function (job){
var cloneJob = angular.extend(job);
location.href = '#/jobs/add';
}
This outputs a lot of json (all the correct data) and it goes to the add page.
Try something like
<tr ng-repeat="whatever in whatevers"><button ng-click="duplicateItem(whatever)">duplicate</button></tr>
And on the controller:
$scope.duplicateItem = function(item){
$scope.duplicatedItem = angular.copy(item); //this will do a copy, not just assign a reference.
//if you need clean the duplicate item
delete $scope.somePropertyYouWannaClean;
}
It would better if you provided a working example fiddle or at least more code, so we can give you more accurate answers.
Edit:
A cleaner way would be to make the clone function load the info into a service (or factory, a singleton). Then after loading the route you use that service to get the content back and play with it.
Like:
angular.module('some.namespace.factory', [])
.factory('CloneJobFactory', function () {
return {
job: null,
loadJob: function (job) {
var auxJob = angular.copy(job);//if you just need a shallow copy use angular.extend
this.job = this.cleanJob(auxJob);
},
getClonedJob: function(){
return this.job;
},
cleanJob: function(job) {
//code that cleans a job object that has been cloned
delete job.propertyYouDoNotWantToKeep;
return job;//return the cleaned job
}
};
});
Then the clone function that would be in the controller (that now has to inject the factory we just made) just has to wrap the loadJob method:
$scope.cloneJob = function (job) {
CloneJobFactory.loadJob(job);
}
The same for the function that would use the cloned data:
$scope.someFunction = function (whateverParams) {
var clonedJob = CloneJobFactory.getClonedJob();
//whatever you want
}
This can still be improved.
NOTE: Angular singletons are made to, among other things, share info between controllers, services and so on.
Make a new 'clone' route, that uses the same controller and view as your 'add' route, but passes in the id of the job that should be cloned:
.when('/jobs/add', { templateUrl: 'jobs/add', controller: 'AddController' })
.when('/jobs/clone/:id', { templateUrl: 'jobs/add', controller: 'AddController' })
Then, in the AddController, check if an id has been passed using $routeParams. If there is an id, fetch the job with the id, and initialize the model by cloning the job. If there's no id, initialize the model with an 'empty' job.
myModule.controller('AddController', function($scope, $routeParams){
if($routeParams.id) {
//TODO get existing job using $routeParams.id
$scope.newJob = angular.copy(job);
} else {
$scope.newJob = {};
}
});
I am making CRUD app for learning purpose. I need to update existing javascript array on click of edit button. However currently its not updating the existing array rather then its creating new record. Below is the JS code of controller
For Add screen below is the controller code
.controller('addController', ['$scope','$location','$rootScope', function(scope,location,rootScope){
scope.save = function (){
scope.personName = document.getElementById('name').value;
scope.personDesc = document.getElementById('desc').value;
scope.person = {'name' : scope.personName, 'desc' : scope.personDesc};
if(typeof rootScope.crew === 'undefined'){
rootScope.crew = [];
}
rootScope.crew.push(scope.person);
location.path("/");
}
}])
For Edit Screen, below is the code of controller :-
.controller('editController',['$scope','$location','$routeParams','$rootScope', function(scope,location,routeParams,rootScope){
var oldName = scope.crew[routeParams.id].name;
document.getElementById('name').value = scope.crew[routeParams.id].name;
document.getElementById('desc').value = scope.crew[routeParams.id].desc;
scope.editSave = function(){
scope.person = {
'name' : document.getElementById('name').value,
'desc' : document.getElementById('desc').value
}
rootScope.crew.push(scope.person);
location.path("/");
}
}])
Currently I am adding record in existing array rather updating.
Please suggest
The problem is you are pushing a new item to the array. You need to just update the existing person with the person in scope.
.controller('editController',['$scope','$location','$routeParams','$rootScope', function(scope,location,routeParams,rootScope){
var person = scope.crew[routeParams.id]
scope.person = {
name = person.name,
desc = person.desc
};
scope.editSave = function(){
scope.crew[routeParams.id] = scope.person;
location.path("/");
}
}])
In your edit view you would have this:
<input type="text" id="name" ng-model="person.name"/>
<input type="text" id="desc" ng-model="person.desc"/>
It's also worth mentioning that there is no need to have code such as document.getElementById as angular will handle the model binding for you so you don't have to interact with the dom using javascript.
Every object that you are pushing in array must be identified by some id.So assign one id attribute to the person object that you are pushing.
Now come to the edit.html
<tr ng-repeat="p in person">
{{p.name}}
//In button I am passing id which I used in editing the person object
<button ng-click="edit(p.id)"></button>
</tr>
//In controller
edit(id){
//firstly search for the person which is going to be updated
for(i=0;i<arrayInWhichYouArePushingData.length;i++)
{
if(arrayInWhichYouArePushingData[i].id==id)
{
arrayInWhichYouArePushingData[i]=UpdatedData;
break;
}
}
This is just an algorithm to solve this type of problem.You have to modify little bit.
I have a view that is filled with dropdownlists to filter a report. I also have a view of saved filters that are displayed as links. When a user clicks on their saved filters, I want the appropriate values of the dropdownlists to be selected. The drop downs are being populated properly. On the saved filter link there is an ng-click that will call a function that iterates through the collection of saved filter values and automatically selects the correct one. I cannot figure out how to programmatically set the selected option. Any help is much appreciated!
<select uid="locSelect"
class="span12"
ng-model="reportDetail.selectedLoc"
ng-options="loc.dbid as loc.serviceName for loc in reportDetail.locList | orderBy:'name'">
<option uid="unselectedLocOption" value="">-- Select One --</option>
</select>
Here is the list of saved filters:
<div class=" well fixed-search" style="overflow-x: hidden;overflow-y: auto;">
<div class="well-header">
Saved Filters
</div>
<div ng-if="!hasSavedFilters">
<span>No saved filters</span>
</div>
<ul ng-if="hasSavedFilters" class="nav nav-list dashboard-list">
<li ng-repeat="filter in reportDetail.savedFilters">
<a uid="savedFilter" href="" ng-click="reportDetail.loadSavedFilters(filter.filters)">
<span ng-bind="filter.title"></span>
</a>
</li>
</ul>
And here is my controller
(function(){
'use strict';
var ReportDetailController = function(ReportsService, $scope){
var _locList = {};
var _hospitalStatusList = {};
var _providerStatusList = {};
var _savedFilters = [];
var _sourceTypeList = {};
var _dateRangeList = {};
var _init = function(){
ReportsService.getCurrentReportSavedFilters().then(function(data){
$scope.reportDetail.savedFilters =data;
$scope.hasSavedFilters = ReportsService.hasSavedFilters();
});
ReportsService.getLOCListForDDL().then(function(data){
$scope.reportDetail.locList = data;
//$scope.reportDetail.selectedLoc = $scope.reportDetail.locList[0];
});
ReportsService.getSelectListData()
.then(function(data){
$scope.reportDetail.sourceTypeList = data.CONNECTION_TARGET_STATUS;
$scope.reportDetail.hospitalStatusList = data.CONNECTION_SOURCE_STATUS;
});
ReportsService.getDateRangesForDDL()
.then(function(data){
$scope.reportDetail.dateRangeList = data;
});
$scope.reportDetail.providerStatusList = ReportsService.getProviderStatusForDDL();
};
var _loadSavedFilters = function(filters){
for(var i = 0, l = $scope.reportDetail.locList.length; i<l; i++){
if($scope.reportDetail.locList[i].serviceName == filters.levelOfCare){
$scope.reportDetail.selectedLoc = $scope.reportDetail.locList[i];
console.log($scope.reportDetail.selectedLoc);
}
}
}
var _isActive = function(filter){
for(var i = 0, l = $scope.reportDetail.savedFilters.length; i<l; i++){
if(filter.title == $scope.reportDetail.savedFilters[i].title){
return true;
}
return false;
}
}
var _generateReport = function(){
return ReportsService.generateReport();
};
$scope.reportDetail = {
init: _init,
selectedLoc: null,
isActive: _isActive,
locList: _locList,
selectedHospitalStatus: 'NOTIFIED',
hospitalStatusList: _hospitalStatusList,
selectedProviderStatus: 'NEW',
providerStatusList: _providerStatusList,
selectedSourceType: 'CONNECTED',
sourceTypeList: _sourceTypeList,
selectedDateRange: '',
dateRangeList: _dateRangeList,
savedFilters: _savedFilters,
loadSavedFilters: _loadSavedFilters,
generateReport: _generateReport
};
$scope.reportDetail.init();
};
app.controller('ReportDetailController', ['ReportsService', '$scope', ReportDetailController]);
})();
You just need to set the ng-model to whatever it should be, so in this case you would set reportDetail.selectedLoc to whatever loc.dbid it should be.
For example: http://jsfiddle.net/uWLua/1/
Note: Make sure they have the same type, so in your example make sure they are either both integers, or both strings, it will not know they are the same if you have one as 5073 and one as "5073"
I updated the fiddle to show that the string and number do not do the same thing.
The ng-model and the expression feeding ng-options -must- match in order for Angular to compare values and see what option is 'selected'. Just as 'dave' indicated.
Due to time constraints I ended up going a different route. I created an event bus of sorts in my service layer and subscribe to the even in my controller, updating the model, and used ng-repeat with ng-selected.
I'm still interested to understand why this was not working with ng-options. The model and ng-options types matched, and everything appeared to be wired up correctly. When I have more time i'll re-address the original issue. Thanks for all who responded!
You need custom directive, or something similar to this two approaches
<div ng-controller="MyCtrl">
<h1>Approach 1</h1>
<span ng-repeat="val in dbs">
<input type="checkbox" ng-model="val.checked">{{val.name}}
</span>
<hr/>
<h1>Approach 1</h1>
<select multiple>
<option ng-repeat="val in dbs" name="val.name" value="val.name" ng-selected="val.checked">{{val.name}}</option>
</select>
<h4>Source (note scope changes)</h4>
{{dbs}}
</div>
also you can use ng-change to do some complex ops
If I understand, in summary, you have a select filled with a list, and you want to programmatically set one of those to be selected, type it as the default right?
If so, you can easily solve this with ng-options, just associate your controller instance with scope and assign the position of the list you want to the model of select, for example:
Select HTML
<select ng-model="vm.aluno_id" name="aluno_id" ng-options="aluno.nome for aluno in alunos">
Controller
app.controller("auxiliarController", function( $scope){
//instancia controller;(Controller instance;)
var vm = this;
$scope.vm = vm;
//carregando lista no scope, que serĂ¡ utilizado pelo angular no select
//Loading list in scope, which will be used by angular in select
$scope.alunos = [{id: 1, nome: "aa"}, {id: 2, nome: "bb"}];
//setando item default no select
$scope.vm.aluno_id = $scope.alunos[0];
});
I hope I have helped