Argument 'NavController' is not a function, got undefined - html

i get this error when i start the app
this is the controller:
myApp
.controller('NavController',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'main';
return page === currentRoute ? 'active' : '';
};
}]);
and this is the app.js:
angular.module('myApp',[
'ngRoute'])
.config(['$routeProvider',
function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'views/main.html',
controller: 'mainCtrl'
})
.when('/team1',{
templateUrl:'views/team1.html',
controller: 'mainCtrl'
})
}]);
and the htmlIndex where i use the contoller:
<header>
<div class="container">
<div class="navbar">
<ul class="nav navbar-nav" ng-controller="NavController">
<li ng-class="navClass('home')"><a href='#/'>Home</a></li>
<li ng-class="navClass('home')"><a href='#/team1'>team1</a></li>
</ul>
</div>
</div>
</header>
i click the nav buttons nothing happens and in the console i get this error "Argument 'NavController' is not a function, got undefined"

Maybe you call controller in a wrong way. It should be called on a app like this:
angular.module('myApp')
.controller('NavController',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'main';
return page === currentRoute ? 'active' : '';
};
}]);
Take a look at this fiddle for a complete code: https://jsfiddle.net/q91jozyr/

When you define the module with angular.module('myApp', ['ngRoute']) you need to save the reference in the variable myAppto reuse the module, when declaring the controller.
app.js:
var myApp = angular.module('myApp', ['ngRoute'])
Alternatively I suggest to call the controller by reusing the module like this:
controller:
angular.module('myApp').controller('NavController', [ /* etc... */ ]);
Note that the module is being reused, if you don't specifiy the dependencies again like angular.module('myApp') instead of angular.module('myApp', [ ]).
In both cases make sure the module myApp is bootstrapped by adding ng-app="myApp" to any of the parent elements, e.g. the <body>:
<body ng-app="myApp">

Related

how to call JSON data through URL in Angular JS

I'm practicing Web API through JSON.
In the URL I am using (https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=malaria&format=json), there are fields like ID, titles etc. I want to call title and display it. Below is my code so far:
app.controller("europepmc", ['$scope', '$http', function($scope, $http) {
$http.get('https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=malaria&format=json')
.success(function(data) {
$scope.magazine = data;
});
}]);
And my controller is binding with html date in the following way:
<div ng-controller="europepmc">
<p>The magazine title is is {{magazine.title}}</p>
</div>
After successfully developing this code I'm not able to get the title.
The JSON you are receiving has more properties for you to go through before you can reach title from results. You should extent it with .resultList.result first. Then display this array with ng-repeat.
Here is a demo:
var app = angular.module("pmc", []);
app.controller("europepmc", ['$scope', '$http', function($scope, $http) {
$http.get('https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=malaria&format=json')
.then(function(res) {
$scope.magazines = res.data.resultList.result;
});
}]);
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="pmc" ng-controller="europepmc">
<div ng-repeat="magazine in magazines">
{{magazine.title}}
<hr>
</div>
</div>
</body>
</html>
Here is a demo to view the entire response:
var app = angular.module("pmc", []);
app.controller("europepmc", ['$scope', '$http', function($scope, $http) {
$http.get('https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=malaria&format=json')
.then(function(res) {
$scope.magazine = res.data;
});
}]);
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="pmc" ng-controller="europepmc">
<pre>
{{magazine | json}}
</pre>
</div>
</body>
</html>
your Json object does have the title property, but a bit deeper:
object.resultList.result.0-24.title
to look at it better, paste your Json here:
http://jsonviewer.stack.hu/
and check the viewer tab.
//In Angular Controller Code
var app = angular.module("myApp", []);
app.controller("europepmc", ['$scope', '$http', function ($scope, $http) {
$http({
method: 'GET',
dataType: 'json',
url: 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=malaria&format=json',
}).then(function (success) {
$scope.magazineList = success.data.resultList.result;
}, function (error) {
alert(error);
});
}]);
// HTML Page Code
Use ng-repeat to loop through mg in magazineList -- and then use mg.title

Can't inject HTML into an angular page

I want to inject html into an angular page
My controller starts with:
myapp.controller("myCtrl", function ($scope, $http, $stateParams, $sce) {
$scope.renderHtml = function(html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.pgf = "<p>Hello</p>";
And on my HTML page I have:
<div class="intro"> AA {{renderHtml(pgf)}} AA </div>
And in the browser, I see:
AA <p>Hello</p> AA
Where what I want is
AA
Hello
AA
Is this a version problem- how do pick a consistent set of versions? (If I just raise the versions, I get all sorts of errors...)
You have to use ng-bind-html (angular ngBindHtml docs) to bind HTML content...
CONTROLLER
function myCtrl($scope, $sce) {
$scope.renderHtml = function(html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.pgf = "<p>Hello I'm a Bear</p>";
}
HTML
<div ng-bind-html="renderHtml(pgf)"></div>
Additionally, here you are a working PLUNKER with your example.
So your Angular code works but you didn't place your html binding in the right place.
You can't set a function inside angular binding {{ function }}
So in your HTML should say <div ng-bind-html="trustHTML(pgf)"></div>
Try ngBindHtml directive in module ng. It provides a secure way of binding content to an HTML element.
Syntax :
<element ng-bind-html="expression"></element>
DEMO
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {
$scope.renderHtml = function(html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.pgf = "<h1>Hello I'm a Bear</h1>";
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-bind-html="renderHtml(pgf)"></div>
</div>

How to pass data between pages in Ionic app

I have had a look at all the examples around and tried to integrate with my Ionic project and failed. Here is what I have so far.
I am using a project created using creator.ionic.com
I have an html page that im loading a JSON file into
(agentSchedule.html)
<ion-view style="" title="Agent Schedule">
<ion-content class="has-header" overflow-scroll="true" padding="true">
<ion-refresher on-refresh="doRefresh()">
</ion-refresher>
<div ng-controller="agentScheduleCtrl">
<ion-list style="">
<ion-item class="item-icon-right item item-text-wrap item-thumbnail-left" ng-repeat="user in users">
<img ng-src="{{ user.image }}">
<h2>{{ user.fname }} {{ user.lname }}</h2>
<h4>Role : {{ user.jobtitle }}</h4>
<h4>Username : {{ user.username }}</h4><i class="button-icon icon ion-ios-arrow-forward"></i>
</ion-item>
</ion-list>
</div>
</ion-content>
Here is the controller and routes for that page
.controller('agentScheduleCtrl', function($scope, $http, $timeout) {
var url = "http://www.otago.ac.nz/itssd-schedule/mobileappdevice/services/getUsers.php";
var url = "users.json";
$http.get(url).success( function(response) {
$scope.users = response;
});
.state('menu.agentSchedule', {
url: '/page4',
views: {
'side-menu21': {
templateUrl: 'templates/agentSchedule.html',
controller: 'agentScheduleCtrl'
}
}
})
I am another page that I want to pass the username to, and then use on any page that I go from there
(specificAgentDetails.html)
<ion-view style="" view-title="Agent Specific Schedule">
<ion-content class="has-header" overflow-scroll="true" padding="true">
</ion-content>
</ion-view>
Here is the controller and routes for that page
.controller('specificAgentDetailsCtrl', function($scope) {
})
.state('menu.specificAgentDetailsCtrl', {
url: '/page9',
views: {
'side-menu21': {
templateUrl: 'templates/specificAgentDetailsCtrl.html',
controller: 'specificAgentDetailsCtrl'
}
}
})
How to Pass the user.username JSON variable to the next page as a global variable ??
Any help would be awesome - im going around in circles
So what #shershen said is true most ionic apps are set up as SPA's, what you're going to do isn't a "ionic" thing it's more of a AngularJS thing. You're going to want to setup a Service to hold your User info and then share it with your other controllers.
Create a Factory to share the data.
Inject the factory into the first controller and set it.
Inject the factory into the second controller and retrieve it.
Share data between AngularJS controllers
If you're familiar with get/set in OOP you should have no problem.
.factory('Data', function () {
var user = {};
return {
getUser: function () {
return user;
},
setUser: function (userparameter) {
user = userparameter;
}
};
})
.controller('agentScheduleCtrl', function($scope, $http, $timeout, Data) {
var url = "http://www.otago.ac.nz/itssdschedule/mobileappdevice/services/getUsers.php";
var url = "users.json";
$http.get(url).success( function(response) {
Data.setUser(response);
$scope.users = response;
});
Then in your second controller:
.controller('specificAgentDetailsCtrl', function($scope, Data) {
$scope.user = Data.getUser();
})
Make sure the syntax between the view and controllers are correct. I'm using user you're using users, setup breakpoints in your controllers to see what's going on there.
I use a little generic factory to do the job.
.factory('LocalRepo', function () {
var data = {}
return {
Get: function (key) {
return data.key;
},
Set: function (key, val) {
return data.key = val;
}
}
})
.controller('One', function($scope, LocalRepo) {
//Set in first controller
//TODO: $scope.users = .... from your call
LocalRepo.Set('users', $scope.users);
})
.controller('Two', function($scope, LocalRepo) {
//Get in second controller
$scope.users = LocalRepo.Get('users');
})
Use it to set whatever you want between controllers
Here is a quite simple solution. use $window and it will hold the data globally available for all controllers, services or anything etc.
.controller('agentScheduleCtrl', function($scope, $http, $timeout,$windows) {
$window.users = [];
var url = "http://www.otago.ac.nz/itssd-schedule/mobileappdevice/services/getUsers.php";
var url = "users.json";
$http.get(url).success( function(response) {
$window.users = response;
});
})
Inject $window as dependency in other controller and you can access it like $window.users.
Hope it helps someone.

Understanding scope in directive's childs

I'm trying to understand "scopes" in agularJS and i can't understand the following piece of code:
HTML:
<body ng-app="myModule">
<div ng-controller="MyCtrl">
<my-component>
<h2>Attribute</h2>
{{isolatedAttributeFoo}}
</my-component>
<my-component>
<h2>Attribute</h2>
{{isolatedAttributeFoo}}
</my-component>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="app.js"></script>
AngularJS:
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.isolatedAttributeFoo = 'Hello!';
}]);
As you can see it is a very simple test. As far as i know (from this example), the childs of a directive (in the example, the elements inside "my-component") inherit the scope from the directive and, since the "my-component" scope is isolated, the "isolatedAttributeFoo" variable should NOT take the value from the "isolatedAttributeFoo" variable at the controller... But it does. Why? Am i misunderstanding something?
If you want to try it, here is the Fiddle.
You can only isolate the scope when you include the template or templateUrl in the directive definition. Other wise it will only inherit from parent and view won't even recognize any changes to scope made in link or controller of directive
Try the following:
HTML
<my-component></my-component>
JS
.directive('myComponent', function () {
return {
restrict:'E',
template: ' <h2>Attribute</h2>{{isolatedAttributeFoo}}',
scope:{},
link:function(scope){
scope.isolatedAttributeFoo = 'Good Bye!';
}
};
});
DEMO
I think this will be clear:
Here is a fiddle:
https://jsfiddle.net/kst65t0p/3/
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{},
link : function(scope){
alert(scope.isolatedAttributeFoo);
}
};
})
.controller('MyCtrl', ['$scope', function () {
this.isolatedAttributeFoo = 'Hello!';
}]);
<div ng-app="myModule" ng-controller="MyCtrl">
<my-component>
<h2>Attribute</h2> {{MyCtrl.isolatedAttributeFoo}}
</my-component>
<my-component>
<h2>Attribute</h2> {{MyCtrl.isolatedAttributeFoo}}
</my-component>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Your scope is isolated into the link function.
The link function is to a directive what a controller is to the view.

Angularjs UI-router not working and no error message

I'm new to angularjs and I'm trying to set up my ui-routes. When I go to the page, I click on the button that sends you to the route and nothing happens (not even an error message). This is what my routing configure looks like ...
var route = angular.module('route', ["ui.router", 'ngResource'])
// configure the routing
route.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
// send to profile page
$urlRouterProvider.otherwise("/user_stats");
$stateProvider
// route for personal info
.state('index', {
url: "/user_stats",
templateUrl : "statistics/user_stats.html" ,
controller : 'user_statsController'
})
});
And this is my html file with the button and view
<!-- navigation bar -->
<div class="wrapper" ng-controller="HeaderController" style="margin-top:8px">
<ul class="nav nav-pills">
<li ng-class="{ active: isActive('/user_stats')}"> <a ui-sref="user_stats"><span class="glyphicon glyphicon-eye-open"></span> Statistics</a></li>
</ul>
</div>
<!-- route veiw -->
<div class="container" id="route" style="width:90%">
<div ui-view></div>
</div>
Any ideas? Thanks in advanced
I think the comment //route for personal info looks in an odd position and I also prefer this to declare routes:
$stateProvider.when('/', {
url: "/user_stats",
templateUrl : "statistics/user_stats.html" ,
controller : 'user_statsController'
}).otherwise({ redirectTo: '/' });
You have to do some work on configuration. see the code sample below
route.config(['$routeProvider', '$locationProvider', '$stateProvider', function ($routeProvider, $locationProvider, $stateProvider) {
var home = {
name: 'home',
controller: 'HomeController',
templateUrl: '../shell/home.html',
pageTitle: ''
},
login = {
name: 'login',
controller: 'loginController',
templateUrl: '../../authentication/login.htm',
pageTitle: ''
},
signatories = {
name: 'signatories',
controller: 'SignatoriesCtrl',
templateUrl: '../signature/signatories.htm',
pageTitle: "Signatories"
};
$stateProvider.state(home);
$stateProvider.state(login);
$stateProvider.state(signatories);
$locationProvider.html5Mode(true);
} ]).run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
} ]).controller('RootController', ['$scope', '$route', '$routeParams', '$location', '$state', function ($scope, $route, $routeParams, $location, $state) {
} ]);