I am using a module where I add in my first controller which is taking a service as a dependency. All the service is doing is bringing in some data.
Then I have a show function which I am adding on an anchor element in my view in order to be able to click on the the first name and then get the user's details.
My second controller takes the data from the first controller and then using $routeParams I am trying to show the data on the user view.
Is there something I am doing wrong here?
(function() {
var app = angular.module('test');
app.controller('testCtrl', ['$scope', 'testFactory', '$location', function($scope, testFactory, $location) {
testFactory.getContact().then(function(data) {
$scope.contacts = data.data;
});
$scope.show = function(firstname) {
$location.path('main/' + firstname);
};
}]);
app.controller('userCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.user = $scope.contacts[$routeParams.firstname];
}]);
}());
These are the routes
(function() {
var app = angular.module('test', ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "testCtrl"
})
.when("/main/:firstname", {
templateUrl: "contact.html",
controller: "userCtrl"
})
.otherwise({redirectTo:"/main"});
$locationProvider.html5Mode(true);
});
}());
This is the error I am getting in my console:
TypeError: Cannot read property 'any1' of undefined
where any1 is the is the first name.
Related
I am working on a small AngularJS blogging app (the framework version I use is 1.7.8).
I have managed to pull and display posts from an API I made myself.
I have a problem displaying a single post and I can't figure out its cause.
My app.js file:
angular.module('app', [
'ngRoute',
'app.controllers',
'ngSanitize'
]).config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'templates/posts.html',
controller: 'PostsController'
}).when('/:slug', {
templateUrl: 'templates/singlepost.html',
controller: 'SinglePostController'
}).when('/page/:id', {
templateUrl: 'templates/page.html',
controller: 'PageController'
}).otherwise({
redirectTo: '/'
});
}]);
Of my two controllers, only the first works as desired:
// All posts
.controller('PostsController', ['$scope', '$http', function($scope, $http){
$http.get('api').then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// Pages
$scope.pages = response.data.pages;
});
}])
// Single post
.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$http.get('api/{slug}').then(function(response) {
const slug = $routeParams.slug;
console.log(slug); //consoles the slug post
console.log(response.data.post); //consoles null
});
}])
Tthe SinglePostController displays post: null in the console. That puzzles me, especially since:
console.log(slug); shows any posts slug in the console;
replaceing {slug} with an actual slug
("the-future-of-oil", for instance), does display a single posts
data in the console.
Where is my mistake?
I have solved the problem by replacing $http.get('api/{slug}') with $http.get('api/' + slug).
Now, in the controller I have:
// Single post
.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
//Send single post to the view
$scope.post = response.data.post;
});
}])
In the view I have:
<div class="content">
<h1>{{post.title}}</h1>
<div class="meta">Published on {{{post.created_at}} by {{post.first_name}} {{post.last_name}}</div>
<div class="post-content">{{post.content}}</div>
</div>
It works.
Try 'api/:slug'. Instead of {slug} in your http get
I am working on an app about routing, my code:
//HTML, I passed a 'test' into routing
Test
<div data-ng-view=""></div>
//Template
<h1>{{res}}</h1>
//Angularjs
var app = angular.module("dictApp", ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/details/:test', {
templateUrl: 'template.html',
controller: 'testCtrl'
});
}]);
app.controller('testCtrl', function ($scope, $routeProvider) {
$scope.res = $routeProvider.test;
});
//The template is displayed as
{{res}}
The template page should display 'test', but I don't know why it didn't work.
Thansk in advance.
'test' parameter should be available in $routeParams.
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
The service that exposes the route parameters is $routeParams. $routeProvider is the provider used to configure the routes in the app like the one you have done in your code using .when method as well
You need to inject $routeParams and use it instead of $routeProvider
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
edit: I'm using bootstrap, I think bootstrap tab is causing the
problem
View does not get updated after $scope variable update.
$scope.codeData
if i console the $scope.codeData, i can see the data, but does not render in view.
I have to click twice to get the view render correctly.
is there anything wrong with my code??
Thank you.
config
angular.module('SPAroutes', ['ngRoute', 'SPAcontrollers', 'SPAdirectives'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'templates/views/admin.html',
controller: 'adminCtrl',
controllerAs: 'admin'
})
$locationProvider.html5Mode(true).hashPrefix('!');
}]);
Controller.js
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
$scope.codeData = res.data;
console.log($scope.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
admin.html
{{codeData}}
You are mixing up controllerAs with scope as phil mentioned in his comment on question. Instead of using scope here store values insidethis reference something like this.
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
var admin = this;
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
admin.codeData = res.data;
console.log(admin.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
and inside the view: admin.html
{{admin.codeData}}
here is working plunk for your refernce
I originally had my app set up with ng-route and I'm now switching over to ui-route. I used to use "when('/json/galleries/:projectId')" to generate a gallery when a thumbnail was clicked. Now with "state" I can't seem how to pass my projectId to the gallery state to generate my gallery.
App Module
(function() {
'use strict';
var bhamDesignsApp = angular.module('bhamDesignsApp', ['ngAnimate', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ui.router', 'mm.foundation', 'appControllers']);
bhamDesignsApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partials/home.html',
controller: 'ProjectsController'
})
.state('gallery', {
url: '/gallery/:projectId',
templateUrl: 'partials/gallery.html',
controller: 'GalleryController'
});
});
})();
App Controller
(function() {
'use strict';
var appControllers = angular.module('appControllers', []);
appControllers.controller('ProjectsController', ['$scope', '$http',
function ($scope, $http) {
$http.get('app/json/projects.json').success(function(data){
$scope.projects = data;
});
$scope.orderProp = '-year';
}]);
appControllers.controller('GalleryController', ['$scope', '$stateParams', '$http',
function($scope, $stateParams, $http) {
$http.get('app/json/galleries/' + $stateParams.projectId + '.json').success(function(data) {
$scope.gallery = data;
});
}]);
})();
HTML
.row
.small-12.medium-3.columns(ng-repeat="project in projects | orderBy:orderProp | filter:categoryFilter")
.tmbnail-container
a(ui-sref="gallery")
img.tmbnail(ng-src="{{project.thumbnail}}")
.text
h5 {{project.title}}
h6 {{project.year}}
.small-12.medium-6.columns
a(ui-sref="gallery")
You don't pass any ID to the state.
Change it to
a(ui-sref="gallery({projectId: project.id})"
(assuming project has an id field that holds its ID)
Documentation that explains how to use ui-sref: http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref
While implementing a modal for dialog boxes I am getting Error: [ng:areq] Argument 'ModalInstanceCtrl' is not a function, got undefined. I have two controllers in the same .js file. The error shows up the name of the second controller.
ng-app is contained in main html file.
<div ng-app = "LoginApp">
<div ng-view>
<!-- partial will go here -->
</div>
</div>
Angular routes
var LoginApp = angular.module('LoginApp', ['ngResource', 'ngRoute', 'ui.bootstrap'])
LoginApp.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {controller: LoginCtrl, templateUrl: '/js/templates/login.html'})
.otherwise({redirectTo: '/'})
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
LoginCtrl.js file
'use strict'
var LoginCtrl = ['$scope', '$modal', '$log', function($scope, $modal, $log) {
$scope.authenticate = function(){
var loginModal = $modal.open({
templateUrl: 'login-modal.html',
controller: 'ModalInstanceCtrl',
resolve: {
modalData: function () {
return {
user: {
name: '',
password: ''
}
};
}
}
});
loginModal.result.then(function (user) {
$log.info("My name is:" + user.name);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}];
var ModalInstanceCtrl = ['$scope', '$modalInstance', 'modalData', function($scope, $modalInstance, modalData){
}];
In the LoginCtrl.js file, LoginCtrl doesn't shows up this error but the declaration of ModalInstanceCtrl is undefined. Could anyone let me know why is this happening.
In the param of $modal.open(), change from this:
...
controller: 'ModalInstanceCtrl',
...
To this:
...
controller: ModalInstanceCtrl,
...
Notice, no quotes for the name of the controller, because you want AngularJS to use the ModalInstanceCtrl variable, not a controller registered with angular.
Alternatively, if you want to keep the quotes, you can register ModalInstanceCtrl with AngularJS, like this:
LoginApp.controller('ModalInstanceCtrl', ['$scope', '$modalInstance', 'modalData', function($scope, $modalInstance, modalData){
...
}]);
Either way will work.