I can't seem to solve this issue. I have other controllers done in the same way that work fine but this one gives an error
Error: ng:areq Bad Argument" "Argument 'myCtrl' is not a function, got undefined. Here is my code:
//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
(function(){
var myContacts = angular.module('myApp');
myContacts.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
getContacts(1);
// Page changed
$scope.pageChanged = function(newPage) {
getContacts(newPage);
};
// Get function
$scope.getContacts = function(pageNumber){
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function(data){
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: '+ $scope.contacts);
// Prepare message output
if(data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
})();
// html
<html lang="en" ng-app="myApp">
<head>...
<div data-ng-controller="myCtrl" class="container-fluid" id="pcont">
<table class="table no-border hover">
<thead class="no-border">
<tr>
<th class="text-center"><strong>Position</strong></th>
<th class="text-center"><strong>Organization</strong></th>
</tr>
</thead>
<tbody class="no-border-y">
<tr dir-paginate="contact in contacts | itemsPerPage: request_limit" total-items="totalContacts" current-page="pagination.current">
<td class="text-center"><# contact.contact_position #></td>
<td class="text-center"><# contact.organization_name #></td>
</tr>
</tbody>
</table>
What have I done wrong there?
This line in your controller function probably throws an error, because such a function is not defined:
getContacts(1);
Because of this, the controller is not correctly defined so you get the error that you received by angular.
Try removing that line and instead putting this at the end of your controller function:
$scope.getContacts(1);
As a side note, you have the same mistake in the $scope.pageChanged function.
There you should replace getContacts by $scope.getContacts as well.
Still not getting, why you enclosed the controller in a function(), try this:
//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
myApp.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
getContacts(1);
// Page changed
$scope.pageChanged = function(newPage) {
getContacts(newPage);
};
// Get function
$scope.getContacts = function(pageNumber){
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function(data){
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: '+ $scope.contacts);
// Prepare message output
if(data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
// html
<html lang="en" ng-app="myApp">
<head>...
<div data-ng-controller="myCtrl" class="container-fluid" id="pcont">
<table class="table no-border hover">
<thead class="no-border">
<tr>
<th class="text-center"><strong>Position</strong></th>
<th class="text-center"><strong>Organization</strong></th>
</tr>
</thead>
<tbody class="no-border-y">
<tr dir-paginate="contact in contacts | itemsPerPage: request_limit" total-items="totalContacts" current-page="pagination.current">
<td class="text-center"><# contact.contact_position #></td>
<td class="text-center"><# contact.organization_name #></td>
</tr>
</tbody>
</table>
I can't seem to find error in your code as it is quite tough format . I am just giving a try so try it .
(function () {
var myApp = angular.module('myApp', ['ngMaterial', 'angularUtils.directives.dirPagination']);
myApp.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
var myContacts = angular.module('myApp');
myContacts.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
$scope.getContacts(1);
// Page changed
$scope.pageChanged = function (newPage) {
$scope.getContacts(newPage);
};
// Get function
$scope.getContacts = function (pageNumber) {
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function (data) {
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: ' + $scope.contacts);
// Prepare message output
if (data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
})();// JavaScript source code
Your definition of controller is kinda weird.
Its kinda weird because your controller is not bootstrap with your application.
You can implement controller in these ways :
Method:1
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
myApp.controller('myCtrl', function ($scope, $http) {
// .. Rest of the controller code
Take a look in this guide :
Angular controller guide
Method: 2.
var myApp = angular.module('myApp',['ngMaterial','angularUtils.directives.dirPagination'])
.controller('myCtrl', myCtrl)
function myCtrl($location, common , config) {
}
Please check John papa angular convention here
John Papa Convention
Related
is it possible to pass a $scope variable to another function inside the controller?
the first function is a POST request which included the id.
the second function is a ng-click function which needs the $scope.id variable.
is there a way to pass them ? maybe as a global variable or can i write the $scope.id in the parameter list from the second function.
the second approach is that I pass the parameter in my view with ng-click = "getResult({{id}}, r.id)"
this is my controller:
.controller('HomeController',
['$scope', '$rootScope', 'SendJmeterFile', 'NotificationPollService', 'GetResultFile',
function ($scope, $rootScope, SendJmeterFile , NotificationPollService, GetResultFile) {
$scope.upload = function() {
$scope.dataTable = false;
$scope.id = 0;
$scope.results = "";
var customArtifacts = "";
var testDataBase = "";
if($scope.jmeterFile.customArtifact == undefined){
customArtifacts = null;
} else {customArtifacts = $scope.jmeterFile.customArtifact.base64}
if($scope.jmeterFile.testDataBase == undefined){
testDataBase = null;
} else {testDataBase = $scope.jmeterFile.testDataBase.base64}
SendJmeterFile.upload($scope.jmeterFile.jmeter.base64, customArtifacts, $scope.jmeterFile.customProperties, $scope.jmeterFile.instanceConfiguration, $scope.jmeterFile.instances, $scope.jmeterFile.providerID, testDataBase)
.then(function(data) {
alert("Daten erfolgreich verschickt!");
console.log(data);
console.log(data.data.id);
$scope.dataTable = false;
$scope.id = data.data.id;
var poller = new NotificationPollService($scope.id);
poller.promise.then(onSuccess, onError, onNotify);
function onSuccess(data) {
// data.status == "DONE"
console.log("done controller" + data);
$scope.dataTable = true;
$scope.results = data.data.results;
};
function onError(data) {
// data.status == "ERROR"
console.log(data);
console.log("error controller" + data);
$scope.dataTable = false;
};
function onNotify(data) {
console.log(data);
// data.status == "TEST" || data.status == "SETUP"
console.log("test/setup controller" + data);
$scope.dataTable = false;
};
});
}, function(data) {
alert("Fehler!");
console.log("else controller" + data);
$scope.dataTable = false;
};
$scope.getResult = function() {
GetResultFile.getResult(id, rid)
.then(function(data) {
console.log("Download erfolgreich");
console.log("data.status");
});
}, function(data) {
console.log("Download ERROR!");
console.log(data.status);
};
EDIT
i try it with this approach:
$scope.getResult = function(rid) {
GetResultFile.getResult($scope.id, rid)
.then(function(data) {
console.log("Download erfolgreich");
console.log("data.status");
});
}, function(data) {
console.log("Download ERROR!");
console.log(data.status);
};
this is the call in my view from $scope.upload:
<span ng-show="dataTable">
<table>
<tr ng-repeat="r in results">
<td><a ng-click="getResult(r.id)" download>{{r.results.name}}</a></td>
</tr>
</table>
</span>
this is from the $scope.getResult:
<span ng-show="dataTable">
<table>
<tr ng-repeat="r in results">
<td><a ng-click="getResult(r.id)" download>{{r.results.name}}</a></td>
</tr>
</table>
</span>
is it possible to pass a $scope variable to another function inside
the controller ?
$scope is injected as a parameter to the controller function, so all functions defined inside the controller have access to the $scope through closure
.controller('mycontroller', function($scope) {
function makesPostRequest() {
console.log($scope);
}
$scope.getResult = function(params) {
console.log($scope);
}
});
So, given your example, this should do it:
$scope.getResult = function (rid) {
GetResultFile.getResult($scope.id, rid)
^^^^^^^^^
.then(function (data) {
console.log("Download erfolgreich");
console.log("data.status");
}, function (data) {
console.log("Download ERROR!");
console.log(data.status);
})
};
My problem started when I tried to add a library SignalR in my AngularJs project. I do not know why but the data flow has stopped working properly, I mean that when I try to insert an object into an array I do not see it, but when I try to add another one I see first object, and when I try to add a third object I see only the second.
edit : all code in the angular controller.
app.controller('HomeCtrl', ['$scope', 'HttpSrv', '$state', function ($scope, HttpSrv, $state) {
$scope.messages = [];
activate();
function activate() {
if (HttpSrv.CheckToken()) {
loadPage();
}
};
$scope.$on("$destroy", function () {
con.stop();
});
function connectToChat() {
HttpSrv.http('GET', 'home/GetChatToken').then(function (res) {
localStorage.setItem('ChatToken', res.Result);
con.start({ jsonp: true }, function () { console.log('Start'); });
});
}
var con = $.hubConnection("http://localhost:4704/");
var hub = con.createHubProxy('ChatHub');
hub.on('fail', function (res) {
console.error(res);
});
hub.on('addMessage', addMessage);
$scope.trySend = function () {
hub.invoke('SendMessage', localStorage.getItem('ChatToken'), document.getElementById('messageBox').value);
};
function addMessage(name, message, elementId) {
var tempMessage = '<li id="' + elementId + '" class="right clearfix"><div class="chat-body clearfix">'
tempMessage += '<div class="header"><strong class="pull-left primary-font">' + name + ': </strong> <br />'
tempMessage += '</div><p>' + message + '</p></div></li>'
document.getElementById('chatBody').innerHTML += tempMessage;
document.getElementById('messageBox').value = '';
document.getElementById(elementId).scrollIntoView();
document.getElementById('chatBody').focus();
}
function loadPage() {
HttpSrv.http('GET', 'home/get').then(function (res) {
//console.log(res);
if (res.Status == 200 && res.Succeeded) {
connectToChat();
for (var i = 0; i < res.ListResult.length; i++) {
res.ListResult[i].CreateDate = res.ListResult[i].CreateDate.replace('T', ' ').slice(0, 19);
}
$scope.newsList = res.ListResult;
}
});
};}]);
(i use document.getElementById because of the problem)
First, you shouldn't be building markup in your code. Simply add the message to the list and use ng-repeat in your markup.
However, you also must make sure you use $scope.$apply() or $scope.$digest() when you are processing messages from signalR.
function addMessage(name, message, elementId) {
$scope.$apply(function(){
$scope.messages.push(message);
});
}
I have been attempting to create a script that grabs session data from a PHP API using Angular JS to create authentication.
I have created a factory called User and in my loginController I use User.Initialise() to check whether the session in PHP has a user_id attached to it.
When using User.Initialise() in my loginController (bare in mine my session has a user attached to it) it will use $location.path("/dashboard") to change the route to the dashboard. The dashboard route has a controller that has the variable $scope.UserID which is assigned using User.Session.user_id, however, when I attempt to call User.Session it returns undefined, even though User.Initialise(); assigns it in the loginController.
Can anybody shed some light on this?
var $Gladium = angular.module("Gladium", ["ngRoute", "ngAnimate", "ngSanitize"]);
$Gladium.config(function($routeProvider, $locationProvider){
$routeProvider.when("/",{
templateUrl: "pages/login.html",
controller: "loginController"
}).when("/dashboard",{
templateUrl: "pages/dashboard.html",
controller: "dashboardController"
}).when("/error/:error_code", {
templateUrl: "pages/system_error.html",
controller: "errorController"
});
});
/* Controllers */
$Gladium.controller("dashboardController", function($scope, User){
console.log("Services:");
console.log(User.Session);
});
$Gladium.controller("loginController", function($scope, $location, User){
User.Initialise().then(function(){
$scope.Authenticate = true;
if(User.loggedIn()){
$location.path("/dashboard");
}
});
/* Variables */
$scope.Email;
$scope.Password;
$scope.Login = function(){
if(User.logIn($scope.Email, $scope.Password)){
$location.path("/dashboard");
return true;
}
}
});
$Gladium.controller("errorController", function($scope, $routeParams){
$scope.Errors = {
"request": "We couldn't process that request at this time. Please try again later.",
"unknown": "An unknown error occurred if this is persistant please contact technical support."
};
$scope.currentError = $scope.Errors[$routeParams["error_code"]];
});
/* Factories */
$Gladium.factory("User", function($http, $location){
var Session;
var Error;
return {
Initialise: function(){
return $http.get("core.php?do=getSession").then(function(requestData){
if(requestData.data["requestStatus"] == 1){
Session = requestData.data.data;
}else{
$location.path("/error/request");
return false;
}
});
},
loggedIn: function(){
if(Session["user_id"] != 0){
return true;
}else{
return false;
}
},
logOut: function(){
if(Session["user_id"] != 0 ){
$http.post("core.php",{
do: "logout"
}).then(function(requestData){
if(requestData.data["requestStatus"] == 1){
}else{
}
});
}else{
console.warn("There is no user session to logout.");
}
},
logIn: function(Email, Password){
$http.post("core.php",{
do: "login",
email: Email,
password: Password
}).then(function(requestData){
if(requestData.data["requestStatus"] == 1){
Data = requestData.data;
if(Data["actionStatus"] == 1){
Initialise();
}else{
Error = Data["Error"];
return false;
}
}else{
$location.path("/error/request");
return false;
}
$location.path("/error/unknown");
return false;
});
}
}
});
I think that u just forget to return the Session variable which should be a property of User Service
....
$Gladium.factory("User", function($http, $location){
var Session;
var Error;
return {
// return the Session so it can be accessed via User.Session, or it is a variable in private closure
Session:Session
Initialise: function(){
return $http.get("core.php?do=getSession").then(function(requestData){
if(requestData.data["requestStatus"] == 1){
Session = requestData.data.data;
}else{
$location.path("/error/request");
return false;
}
});
},
....
UPDATE
Sorry the change above won't solve your problem since you are assigning the Session closure variable, which will not change User.Session.In this way it still remains undefined.
There are several ways for you to solve this problem.
One i think that is the most simple is to keep the Session private and access it via a get function User.getSession().
$Gladium.factory("User", function($http, $location){
var Session;
var Error;
return {
// use get function to get Session
getSession:function(){
return Session;
},
Initialise: function(){
return $http.get("core.php?do=getSession").then(function(requestData){
if(requestData.data["requestStatus"] == 1){
Session = requestData.data.data;
}else{
$location.path("/error/request");
return false;
}
});
},
....
In this way u can access your Session by User.getSession().
I am trying to bind from a http get request. The http get is returning true or false. I have tested the get and it is returning properly. When I run the code below, it shows the alert(1111) properly also. However, when I'm trying to change the button text, nothing appears! I have tried everything that I know to do. Any advice would be helpful.
Post.js
myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {
var status = "";
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
$scope.statusMessage = data;
} else {
//Following - show Follow
$scope.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}]);
Html
<span style="float: right" ng-controller="FollowController as follow">
<button type=" button" class="btn btn-success" onclick="location.href='#Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
{{ follow.statusMessage }}</button>
</span>
You should bind the variables to this instead of $scope as you are using controllerAs approach
Controller
myApp.controller('FollowController', ['$scope', '$http',
function($scope, $http) {
var status = "";
var follow = this;
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
follow.statusMessage = data;
} else {
//Following - show Follow
follow.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}
]);
I'm just trying to get this to work:
.....
.when('/channel/:id/:slug',{
templateUrl:'views/channel/index.html',
controller:'Channel',
publicAccess:true,
sessionAccess:true
})
.....
app.controller('Channel', ['$scope','$routeParams', function ($scope,$routeParams) {
}]);
app.run(function($rootScope, $location, $route) {
var routesOpenToSession = [];
angular.forEach($route.routes, function(route, path) {
console.log(path);
console.log(route);
route.sessionAccess && (routesOpenToSession.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
var closedToSession = (-1 === routesOpenToSession.indexOf($location.path()));
if(closedToSession && $rootScope.session.id_user) {
$location.path('/');
}
});
});
why i can't access the page via site.com/channel/9/my-slug also if $rootScope.session.id_user exists and sessionAccess:true ?
i get redirected to / , while any other static url are ok using sessionAccess:true for example channel/staticparam is ok but with dynamic params it won't work
this is the console log result :
fixed sorry for the stupid question:
/*Not logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location,$route) {
var routesOpenToPublic = [];
angular.forEach($route.routes, function (route, path) {
if(route.publicAccess){ routesOpenToPublic.push(route.regexp); }
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not logged users users
if(routesOpenToPublic.indexOf(next_url_regexp) < 0){
$location.path('/auth/login');
}
});
}]);
/*Logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location, $route) {
if($rootScope.session && $rootScope.session.id_user){
var routesOpenToSession = [];
angular.forEach($route.routes, function (route, path) {
if(route.sessionAccess){ routesOpenToSession.push( route.regexp);}
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not allowed session users
if(routesOpenToSession.indexOf(next_url_regexp) < 0){
$location.path('/');
}
});
}
}]);
i needed to check the route regexp and not the static url path