.controller('ExplorerCtrl', ["$scope", "appServices","$location", 'appSettings', function ($scope, appServices, $location, appSettings) {
$scope.changeLocation = function() {
$location.path('career'?name={{career.Name}});
};
$scope.getCareerList = function(){
appServices.doAPIRequest(appSettings.appAPI.career.overviewList, null, null).then(function(data){
$scope.allCareer = data.data.n;
})
};
How to pass parameter from one controller to another page controller. the career.name I want to b appended in my next page API.
Related
I have the following code set up:
var videoControllers = angular.module('videoControllers', []);
videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){
$http.get('http://localhost:8000/videos/api/video/' + $routeParams.videoId + '/?format=json').success(
function(data){
$scope.video = data;
});
})
This code keeps giving me an error which state that: 'videoControllers.videoControllers is not a function'. The tutorial I am using is written in that manner and it is working, but my project gives me this error. Can anyone please help.
Becuase the keyword is controller while you are using videoControllers. Change your code as below:
var videoControllers = angular.module('videoControllers', []);
videoControllers.controller('VideoDetailController', function($scope, $routeParams, $http){
$http.get('http://localhost:8000/videos/api/video/' + $routeParams.videoId + '/?format=json')
.success(function(data){
$scope.video = data;
});
});
Try this coz in ur code ur not accessing controller
angular.module('videoControllers').controller('VideoDetailController', function($scope, $routeParams, $http){
$http.get('http://localhost:8000/videos/api/video/' + $routeParams.videoId + '/?format=json').success(
function(data){
$scope.video = data;
});
});
I'm creating my first web app in angularjs and can't get the page to update with new values once the user submits text/numbers in an input box.
I'm using Java8, MongoDB, angularJS and twitter bootstrap
HTML:
<td>
<input type="text" class="form-control" placeholder="enter bugnumber" data-ng-model="auditdata.newbugnumber">
<h4>Bug Numbers</h4>
{{a}}
</td>
<td>
<button type="submit" data-ng-click="add(auditdata)" class="btn btn-danger" >Save</button>
</td>
In the HTML above i take input from user in ng-model=auditadata.newbugnumber but on server side it sill gets update in the bugnumber filed. The newbugnumber field is acting like a temp variable which is just used to send the new data to the server. The reason for using the temp variable is to avoid two way binding in angularjs.
I tried using $apply(), $watch and digest in the JS below but can't get the value to be updated in the view. The only way the data gets update in view is when i reload the page which is not an option
app.controller('listCtrl', function ($scope, $http,$route) {
$scope.isCollapsed = true;
$http.get('/api/v1/result').success(function (data) {
$scope.audit = data;
}).error(function (data, status) {
console.log('Error ' + data);
})
$scope.add= function(bugInfo) {
$http.post('/api/v1/result/updateBug', bugInfo).success(function (data) {
bugInfo.newbugnumber='';
console.log('audit data updated');
}).error(function (data, status) {
console.log('Error ' + data);
}
};
});
Update function on server side
public void updateAuditData(String body) {
Result updateAudit = new Gson().fromJson(body, Result.class);
audit.update(
new BasicDBObject("_id", new ObjectId(updateAudit.getId())),
new BasicDBObject("$push", new BasicDBObject().append("bugnumber",
updateAudit.getNewbugnumber())));
}
how bugnumber filed in collection looks like
> db.audit.find({"_id" : ObjectId("5696e2cee4b05e970b5a0a68")})
{
"bugnumber" : [
"789000",
"1212"
]
}
Based on your comment, do the following:
Place all your $http handling i a service or factory. This is good practice and makes reuse and testing easier
app.factory('AuditService', function($http) {
var get = function() {
return $http.get("/api/...") // returns a promise
};
var add = function() {
return $http.post("/api/...") // returns a promise
};
return {
get: get,
add: add
}
});
And then in your controller
// note the import of AuditService
app.controller('listCtrl', function ($scope, $http,$route, AuditService) {
// other code here
// If insert is successful, then update $scope by calling the newly updated collection.
// (this is chaining the events using then())
$scope.add = function(bugInfo) {
AuditService.add().then(
function(){ // successcallback
AuditService.get().then(
function(data){ // success
$scope.audit = data;
},
function(){ // error
console.log('error reading data ' + error)
})
},
function(error){ // errorcallback
console.log('error inserting data ' + error)
})
});
The same approach can be applied to all CRUD operations
I have defined an AngularJS dialog as follows in my angular-app.js:
angular.module('myAPP', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) {
$scope.status = ' ';
$scope.showAdvanced = function(ev,_url) {
$mdDialog.show({
controller: DialogController,
templateUrl: _url,
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
}).then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
And in my HTML page I have this:
<a ng-click="openDetailDialog()">Show details</a>
<script type="text/javascript">
function openDetailDialog(id) {
var id = getValue(id, 'id');
showAdvanced($event,'${readDetailURL}&id=' + id + '/');
}
</script>
The problem is that when I add the function showAdvanced() inside another function, it doesn't work.
When I call this function directly in ng-click, it works.
This works:
<a ng-click="showAdvanced($event,'http:myurl/test/id');">Show details</a>
Why?
First you can't attach or bind something that is not on the $scope, or the controller itself.
<a ng-click="openDetailDialog()">Show details</a>
That's wrong.
And second you can't access variables attached to the scope from plain javascript, 2WDB (two way data binding) just include HTML. And of course angular works with encapsulated scope.
The function ´showAdvanced()actually is part of the$scope`element. When you do this in your html:
<a ng-click="showAdvanced()">text</a>
AngularJs changes that (behind the scenes) to $scope.showAdvanced()
If you want to call it from javascript, you could try and change your function call to
`$scope.showAdvanced()`
How to get value from ng-click and send to laravel for query?
//.html
<div ng-controller="recipientsController">
<div ng-repeat="recipient in recipients | orderBy:'-created_at'" ng-click="select(recipient.id)">
<p class="recipientname">{{ recipient.name }}</p>
</div>
</div>
//xxController.js
$scope.select = function() {
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
}
//xxService.js
get:function(){
var comments = $http.get('api/comments');
return comments;
},
//xxController.php [laravel]
public function index()
{
$comments = DB::table('c')
->join('u', 'c.id', '=', 'u.id')
->select('u.id', 'u.name', 'c.comments', 'c.created_at')
->where('u.id','=', Auth::user()->id)
->orWhere('u.id','=', **39 => this part has to be from ng-click value**)
->orderBy('c.created_at','asc')
->get();
return Response::json($comments);
}
You have passing the recipient.id parameter in your ng-click function but you did't retrieve the parameter in your js function
you need to retrieve the parameter
$scope.select = function(**id**) {
var selectedId=id;//you can check here
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
}
For passing data with $http.get method, there is second argument for [config] you can use that.
see: https://docs.angularjs.org/api/ng/service/$http#get for more reference about get method
Dear all I am having trouble with the scope of my $scope or how should I put it.
I am retrieving the data from my Service successfully but I´m having trouble with accessing $scope.players and $scope.tournament and I think it has something to do with being inside the service call. If I console.out() inside the service call everything is just fine. How can I be able access the data which is inside of the service call.
Version 1:
Here console log simply states undefined.
.controller('SelectCtrl', ['$scope','$stateParams', '$location', '$window','playerService','tournamentService', function ($scope, $stateParams, $location, $window, playerService, tournamentService) {
init();
function init() {
playerService.getPlayers().then(function (data) {
$scope.players = [];
angular.forEach(data, function (player, index) {
$scope.players.push(player.info);
});
});
tournamentService.getTournaments().then(function (data) {
var result = data.filter(function (element) {
if (element.ID == $stateParams.id) {
return true;
} else {
return false;
}
});
$scope.tournament = result;
});
};
console.log($scope.tournament);//undefined
console.log($scope.players); //undefined
}
Version 2:,
Here console log simply states the Object {then: function, catch: function, finally: function} Which is not what I wan´t I want the data to be able to display it in my view.
.controller('SelectCtrl', ['$scope','$stateParams', '$location', '$window','playerService','tournamentService', function ($scope, $stateParams, $location, $window, playerService, tournamentService) {
init();
function init() {
$scope.players = playerService.getPlayers().then(function (data) {
$scope.players = [];
angular.forEach(data, function (player, index) {
$scope.players.push(player.info);
});
});
$scope.tournament = tournamentService.getTournaments().then(function (data) {
var result = data.filter(function (element) {
if (element.ID == $stateParams.id) {
return true;
} else {
return false;
}
});
$scope.tournament = result;
});
};
console.log($scope.tournament);//Object {then: function, catch: function, finally: function}
console.log($scope.players);//Object {then: function, catch: function, finally: function}
}
Your help is really appreciated!
The Services:
.factory('playerService', function ($http,$q) {
return {
getPlayers: function () {
//return the promise directly.
var deferred = $q.defer();
$http.get(webServiceUrl + 'api/Player/GetAllPlayers')
.success(function (data) {
//resolve the promise as the data
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
}
}
})
.factory('tournamentService', function ($http,$q) {
return {
getTournaments: function () {
//return the promise directly.
var deferred = $q.defer();
$http.get(webServiceUrl + 'api/Tournament/GetAllTournaments')
.success(function (data) {
//resolve the promise as the data
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
}
}
})
Part of the view:
<h1 style="display: inline-block; margin-left:15px;">Enter <i>{{tournament.Name}}</i></h1>
<div class="row">
<div class="selectinforow">
<div class="col-xs-2 selectinfo">
<span>{{tournament.EntryFee}}$</span></br>
<span>Entry Fee</span>
</div>
<div class="col-xs-2 selectinfo">
<span>{{tournament.Entries}}</span></br>
<span>Entries</span>
</div>
<div class="col-xs-2 selectinfo">
<span>{{tournament.Size}}</span></br>
<span>Max Size</span>
</div>
<div class="col-xs-2 selectinfo">
<span>{{tournament.StartTime}}</span></br>
<span>Start Date</span>
</div>
<div class="col-xs-2 selectinfo">
<span>{{tournament.Entryfee*tournament.Entries}}$</span></br>
<span>Winnings</span>
</div>
</div>
</div>
So if you read your code carefully you will notice you are using a promise on the following line:
tournamentService.getTournaments().then(function (data) {
// [your data is set here - AFTER the service call runs]
}
// [your print is here - run BEFORE service call runs]
The key to the "then" statement is it isn't executed right away, but is instead run when data is returned from the service call. In other words, you have your print in the wrong spot - I would expect the values to be undefined there. If you move the console.log statements into the promise (then) - I would expect to see the valid values. You can also put a break point in the browser debugger to see the values in the "then" function if you want to validate that things are working. Hope this puts you on the right track!
EDIT
Once the promise completes, angular automatically updates the view. Lets say you have the following in your view (just an example):
<h1 ng-bind="tournament.Title">Default Text</h1>
When the view/page loads you will see "Default Text". After the promise completes, if a tournament has been loaded, angular will automatically update the "h1" to now have the Title for that tournament. This happens because angular automatically runs an "$apply()" after a promise completes.
Your code is executed before the promise response.
If you need to code "procedurally", you should $watch the scope variable as below to detect any changes.
For example:
$scope.$watch('tournament', function() {
console.log($scope.tournament);
}, true);