MainController.js
app.controller("mainController", function($scope, $http){
$scope.movies = [];
$scope.searchFilter = '';
$scope.init = function() {
};
$scope.getMovies = function(){
var movieName = $('#MovieName').val();
var movies = getMovies(movieName); // Gets json
$scope.parseMovies(movies);
};
$scope.parseMovies = function(movies){
$scope.movies = [];
$.each(movies, function( index, value ) {
$scope.movies.push($scope.createMovie(value));
});
};
$scope.createMovie = function(json){
Movie=new Object();
Movie.id=json.id;
Movie.title=json.title;
Movie.year=json.year;
Movie.runtime=json.runtime;
return Movie;
};
});
app.js
var app = angular.module('MoviesApp',[]);
html
<body ng-controller="MovieListCtrl">
<div class="container main-frame" ng-app="MoviesApp" ng-controller="mainController">
<input type="text" id="MovieName" />
<input type="button" data-ng-click="getMovies()" />
<ul>
<li ng-repeat="movie in movies">
{{movie.title}}
</li>
</ul>
</div>
</body>
When I click the button and getMovies() is called the data is retrieved ok but the template does not get filled. Only when I click the button again does it get filled.
The thing is when it is clicked the second time, the template gets filled before the new json is retrieved (I put a breakpoint in the script).
I'm stuck
Related
I am trying to write a todo application in Angularjs in the following code.
function write_controller($scope){
$scope.todos = [{text:'hey all',done:false},
{text:'hello',done:false}];
$scope.addtodo = function(){
$scope.todos.push({text:$scope.todopush,done:false});
$scope.todopush = '';
}
$scope.delete = function(){
var oldtodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldtodos, function(x){
if (!x.done){
$scope.todos.push(x);}
});
};
}
<html ng-app>
<head>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">
</script>
</head>
<body>
<div class = "basic_class" ng-controller = "write_controller">
<ul>
<li ng-repeat = "todo in todos"><input type = "checkbox" ng-model
="todo.done">{{todo.text}}</input></li>
</ul>
<input type = "text"
placeholder = "please add data here"
ng-model="todopush">
</input>
<input type = "button" ng-click ="addtodo()" value ="Click me!!"></input>
<input type = "button" ng-click = "delete()" ng-model="remove" value =
"remove!"></input>
</div>
</body>
</html>
In the following code ,I have the following questions.
How is the delete operation working??
My understanding:
1)It pushes the existing array into a new array
2)It clears the exisitng array
3)Iterates over the new array
3)Checking the done functionality??? (When it says !x.done , is it true or false???)
Any help would be highly appreciated.
Walk through the steps
$scope.delete = function() {
// store existing todos array in variable
var oldtodos = $scope.todos;
// create new empty array for todos
$scope.todos = [];
// loop over previously stored todos
angular.forEach(oldtodos, function(x) {//x is element of the array - a single todo object
// if x.done is not truthy
if (!x.done){
// push this item into `$scope.todos`
$scope.todos.push(x);
});
}
Basically it only pushes the done:false into new version of $scope.todos which effectively removes the done:true
I have a page employee.html with a list of dependents and for each row (li) an inner button with the directive ng-click="editDependent({{dependent.id}})". That button tries to call a modal box.
The employee.html is loaded in a ui_view div from an index.html
I saw that each button in view source with chrome are correctly bound ng-click="editDepedent(1)" and so on.
But at the same time I have an error
angular.min.js:118 Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=11&p3=editDependent(%7B%7Bdependent.id%7D%7D)&p4=%7Bdependent.id%7D%7D)
I'm trying to pass my dependent id to my modal and the previous scope also that contains the info about the employee. So how can I achieve this parameter passing?
This is my main controller
app.controller('EmployeeController', function ($scope, $stateParams, $uibModal, EmployeeService) {
if($stateParams.id){
EmployeeService.getEmployee($stateParams.id).then(function(employee){
$scope.employee = employee;
EmployeeService.setCurrentEmployee(employee);
});
}
$scope.editDependent = function(id){
if(id){
$scope.dependentid = id;
}
var uibModalInstance = $uibModal.open({
templateUrl : 'modal_dependent.html',
controller : 'DependentController',
scope: $scope
});
return uibModalInstance;
}
});
This is my dependent controller to catch the value
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}else{
$scope.dependent = { id : 0 };
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
UPDATE
employee.html
<form name="employee_form">
<div>
<h1> {{employee.name}} </h1>
<h3>Dependents</h3>
<button class="btn bgcolor-rb-main" x-ng-click="editDependent(0)">
Add new
</button>
<ul class="list-inline">
<li x-ng-repeat="dependent in employee.dependents">
<button x-ng-click="editDependent({{dependent.id}})">
Edit
</button><br>
<div>{{dependent.name}}</div>
</li>
</ul>
</div>
</form>
This is my modal_dependent.html
<div class="modal-header">
<h4>Dependent</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" id="txtName" x-ng-model="editableDependent.name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" x-ng-click="discardChanges()">Discard</button>
<button type="submit" class="btn btn-primary" x-ng-click="submitDependent()">Save</button>
</div>
UPDATE
I changed my controller to initialize before $scope.dependent
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
$scope.dependent = { id : 0 };
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
SOLVED
My button changed from this
<button x-ng-click="editDependent({{dependent.id}})">Edit</button>
To this
<button x-ng-click="editDependent(dependent.id)">Edit</button>
i think there is parsing error you have to define
$scope.dependentid = {};
before using it,
or otherwise you can use it as a model (if you are submitting a form on frontend like this)
<input type="hidden" ng-model="dependentid" />
it will be better to understand for me if you edit the code and add some frontend html
I'm trying to use angularjs to create a page that does the following:
Is initially empty, save for a dropdownlist that is automatically
populated with apps.
upon selecting one of those apps, data about it will be called from
another controller to the page.
I was successfully able to get the dropdownlist to automatically populate. however, I'm having issues getting it to make the page with ng-change, which I thing is due to the nested ng-controllers. The chartappsuccessfullogins function is not being called at all in my browser. Can anyone help me? Code is below:
My main html page. Note the use of ng-init:
<div ng-controller="chartsuccessfulapploginsController">
<div ng-controller="allappsController" ng-init="add()">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect" ng-change="chartsuccessfulapploginsController.add(value)">
<option ng-repeat="option in data.availableOptions" ng-init="Index = $index" value="{{data.availableOptions[Index].id}}" ng-model="APPID" >{{data.availableOptions[Index].name}}</option>
</select>
</form>
<hr>
<p> {{data}}</p>
<p> {{data.id[0]}}</p>
<p> {{data.name[0]}}</p>
<tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
</div>
<p>{{returnCount}}</p>
<table border = "1">
<tr>
<td>{{chartObject.data}}</td>
<td>{{returnCount}}</td>
</tr>
</table>
<div google-chart chart="chartObject" style="height:600px; width:100%;"></div>
</div>
My get all apps controller. The html page above relies on this to populate the dropdownlist.
angular.module('scotchApp').controller('allappsController',['$scope', function($scope){
var userurl='';
$scope.add = function(){
userurl = 'http://localhost:8085/rest/uafapp/appslist';
var userdata = {};
var userconfig =
{
headers: {
'Content-Type':'application/json'
}
};
var userPostRequest = $.get(userurl, userdata, userconfig);
var userjson = '{\"USER_DATA_RETRIEVED\" : \"fail\"}';
userPostRequest.done(function(userdata){
userjson = JSON.stringify(userdata);
console.log("userjson :: " + userjson);
var postResponse = jQuery.parseJSON(userjson);
$scope.returnName = postResponse['apps'];
var availableOptionsArray = [];
for(i = 0; i < postResponse['apps'].length; i++){
var availableOptions = {};
availableOptions['id'] = postResponse['apps'][i]['appId'];
availableOptions['name'] = postResponse['apps'][i]['appName'];
availableOptionsArray[i] = availableOptions;
}
var returnData = {};
returnData['repeatSelect'] = null;
returnData['availableOptions'] = availableOptionsArray;
$scope.data = returnData;
console.log($scope.returnData);
$scope.$apply()
});
};
}]);
Part of the controller that defines the chart. It's pretty long, so I didn't include the irrelevant code.
angular.module('scotchApp').controller('chartsuccessfulapploginsController',['$scope','$route','$http','AuthTokenService', function($scope, $route, $http, AuthTokenService){
var appurl = '';
var failedappurl= '';
$scope.add = function(APPID) {
...}
Is your allappsController within your chartsuccessfulapploginsController in your controller file?
It should be inside because allappsController is the child scope, and chartsuccessfulapploginsController is the parent scope. You are trying to access the parent scope from the child scope.
If it is not inside, it thinks that ng-change="chartsuccessfulapploginsController.add(value)" is a new controller.
If that is the issue, the fix would be something like this:
angular.module('scotchApp').controller('chartsuccessfulapploginsController',['$scope','$route','$http','AuthTokenService', function($scope, $route, $http, AuthTokenService){
var appurl = '';
var failedappurl= '';
$scope.add = function(APPID) {} ...
//allappsController inside chartsuccessfulapploginsController
angular.module('scotchApp').controller('allappsController',['$scope',function($scope){
var userurl='';
$scope.add = function(){ ... };
}]);
}]);
Check this out: Use ng-model in nested Angularjs controller
I'm trying to load data into modal using AngularJS. I did the load the data into a list of "cards" and it works fine. But, to each card, I need to open a details modal and to load the rest of the data within it. Follow my code:
//Part of index.html
<body ng-controller="CardsController">
<div class="container">
<div class="cards" ng-repeat="card in cards">
<h3>{{card.user}}</h3>
<button type="button" name="play" title="play" ng-click="toggleModal(card)">Play</button>
</div>
</div>
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{card.user}}</h3> <-- here is my problem!
</my-modal>
// js/controllers/cards-controller.js
angular.module('angstudy').controller('CardsController', function($scope, $http){
$scope.cards = [];
$http.get('http://localhost:3000/api/persons')
.success(function(retorno){
console.log(retorno);
$scope.cards = retorno;
})
.error(function(erro) {
console.log(erro);
});
$scope.modalShown = false;
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
};
});
// js/directives/modal-dialog.js
angular.module('modalDialog', [])
.directive('myModal', function() {
var ddo = {};
ddo.restrict = "E";
ddo.transclude = true;
ddo.scope = {
user: '#user',
show: '='
};
ddo.link = function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
};
ddo.templateUrl = 'js/directives/modal-dialog.html';
return ddo;
});
// js/directives/modal-dialog.html (template for the directive)
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-close' ng-click='hideModal()'>X</div>
<div class='ng-modal-dialog-content'></div>
</div>
</div>
// js/main.js
angular.module('angstudy', ['modalDialog']);
The cards are been displayed normally and the modal opens, but does not display the AE values within the modal (in this case, I'm just testing the value "user", but the json has more data). If I insert just a static value, it displays...
I would've done it by keeping the modal html in a separate file and using a separate controller and I would pass the data to the Modal controller with the resolve keyword.
But since you are using the same controller on both the templates. You can keep a separate variable called $scope.SelectedCard to achieve the functionality.
In your toggleModal method you can assign the card as:
$scope.toggleModal = function(card) {
$scope.modalShown = !$scope.modalShown;
$scope.selectedCard = card;
};
and in the modal you can change to:
<my-modal show='modalShown' width='250px' height='40%'>
<h3>{{selectedCard.user}}</h3> <-- problem solved
</my-modal>
I'm having trouble understanding some of the basics. Here are 2 controllers I have:
<form ng-controller="NewList" id="form" ng-submit="submit()">
<input name="title" ng-model="formData.title" placeholder="{{placeholders.title}}" />
<button type="submit">Generate</button>
<p ng-show="loading == 1">Loading...</p>
<p ng-show="loading == 2">Response: {{response}}</p>
</form>
<div id="lists" ng-controller="GetLists">
<ul>
<li ng-show="loading">Loading...</li>
<li class="list" ng-repeat="list in lists">
<b>{{list.id}}</b> : {{list.title}}
</li>
</ul>
</div>
JS:
function NewList($scope, $http) {
$scope.formData = { };
$scope.placeholders = { "title" : "List title" };
$scope.loading = 0;
$scope.submit = function() {
$scope.loading = 1;
$http.post(window.apiBase + 'lists/create', this.formData)
.success(function(response) {
$scope.response = response;
$scope.loading = 2;
});
}
}
function GetLists($scope, $http) {
$scope.loading = true;
$http.get(window.apiBase + 'lists/all').success(function(response) {
$scope.lists = response.lists;
$scope.loading = false
});
}
What I'm trying to achieve, is upon form submit, refresh the lists. Meaning, when .success() hits in NewList, call GetList and make it happen again. How do I achieve this?