i'm still doing an execise in angularJS to improve my knowledge but now i'm exercizing about routes and i cannot get the controller attributes to work inside the routed template. I've read many tutorial and it should definetly work as it is now So i'm pasting the code snippet.
Javascript
angular.module('greetings', ['ngRoute'])
.service("Addcontent", function($http, $q){
this.name = "Nome";
this.familyName = "Cognome";
me = this;
me.tipi= [];
this.tipi = me.tipi;
this.selectedOption = this.tipi[0];
this.getTipi = function() {
var deferred = $q.defer();
$http.get("http://localhost:8090/my-site/data.json").success(function(data) {
me.tipi = data;
me.selectedOption = me.tipi[0];
deferred.resolve( {options: me.tipi, selectedOption: me.selectedOption} );
}).error(function(){
console.log("error");
});
return deferred.promise;
};
}).controller("renameAddContentController", function($scope, $window, $http, Addcontent, $q, $routeParams, $route){
this.name = Addcontent.name;
console.log(this.name);
this.familyName = Addcontent.familyName;
consolelog(this.familyName);
var ctrl = this;
Addcontent.getTipi().then(function(data) {
ctrl.tipi = data.options;
});
ctrl.selectedOption = $routeParams.showName;
console.log(ctrl.selectedOption);
}).config(function ($routeProvider, $locationProvider){
$routeProvider
.when('/greeted/:showName',
{
controller:'controllers.renameAddContentController',
controllerAs: 'rename',
templateUrl:'/my-site/greeted.html'
})
.otherwise({ redirectTo: '/' })
$locationProvider.html5Mode(true);
});
As you can see there is a service, a controller and a route to be found. The template is very simple:
<h3>Greeting:</h3>
<span>
{{rename.selectedOption}} {{rename.name}} {{rename.familyName}}
<br/>
</span>
And the main html is simple as well:
Greet
<span ng-view>
</span>
(greeting belongs to an other controller not included in this example)...
the error says that the controller is not a function, so it doesn't resolve the attributes mentioned in the template..
Can anyone help?
you controller name in :
$routeProvider
.when('/greeted/:showName',
{
controller:'controllers.renameAddContentController',
controllerAs: 'rename',
templateUrl:'/my-site/greeted.html'
})
should be only renameAddContentController as you defined it earlier, not controllers.renameAddContentController
Related
I have bunch of JSON models in my project and I need to show different models depends on user's actions.
Here is Angular router code:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
}).when('/doc/:section, {
templateUrl: 'views/doc.html',
controller: 'DocCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
And here is DocCtrl.js file:
app.controller('DocCtrl', ['$scope', '$http', 'JSONModelsService',
function ($scope, $http, JSONModelsService) {
var formData = {};
$scope.group = {};
$scope.sections = [];
JSONModelsService.get([section])
.then(function (response) {
console.log(response);
$scope.group = response.data.groups[0];
$scope.sections = $scope.group.sections;
});
}]);
I basically need to make section dynamic so I can show different models in my views. However, I'm confused how I can do it. I just have a folder called JSONModels with multiple json files.
If I understand your question correctly, you are aiming at replacing the [section] part of your code with an actual section identifier?
When a user visits your /doc/:section route, e.g. /doc/my-doc you can access the :section part by injecting the $routeParams service into your controller.
app.controller('DocCtrl', ['$scope', '$http', '$routeParams', 'JSONModelsService',
function ($scope, $http, $routeParams, JSONModelsService) {
...
Using the $routeParams service, you have access to your route parameters. So you can simple access the :section parameter, by reading it off $routeParams.section.
A full example (of what I think you're trying to achieve):
app.controller('DocCtrl', ['$scope', '$http', '$routeParams', 'JSONModelsService',
function ($scope, $http, $routeParams, JSONModelsService) {
var formData = {};
$scope.group = {};
$scope.sections = [];
JSONModelsService.get([$routeParams.section])
.then(function (response) {
console.log(response);
$scope.group = response.data.groups[0];
$scope.sections = $scope.group.sections;
});
}]);
If you would like to know more, take a look at step 7 of the angular tutorial: https://docs.angularjs.org/tutorial/step_07
This is my first attempt to use the Angularjs and I'm trying to create a service and use it inside a controller:
var appTest = angular.module("appTest", ["ngRoute"]);
var appTestControllers = angular.module('appTestControllers', []);
appTest.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$locationProvider.html5Mode(false);
}
]);
appTest.factory("booksApi", function($http){
var _getBooks = function() {
return $http.get('http://localhost/editora-voo/website/books.json');
};
return{
getBooks: _getBooks
};
});
appTest.controller('HomeCtrl', ['$scope', '$http', function($scope, $http, booksApi) {
booksApi.getBooks().success(function(data) {
$scope.books = data;
});
}]);
But it is returning an error: Cannot read property 'getBooks' of undefined
You missed to add booksApi depnedency inside your controller dependency array, You should add it first and then use that inside the function of controller.
Controller
appTest.controller('HomeCtrl', ['$scope', '$http', 'booksApi', //<--missed dependency here
function($scope, $http, booksApi) {
booksApi.getBooks().then(function(response) {
$scope.books = response.data;
});
}]);
Plunkr Here
In my angularjs app, I am trying to pass the data from one cshtml view to another view through routing but in details.cshtml, I don't see the data coming into it though I can see the change in URL
Index.cshtml (View1)
{{addprodtocart}}
Controller.js
app.controller('CartController', function ($scope) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
$scope.cid = cartprd[len];
}
});
Details.cshtml ( I don't see the data coming into the span below)
<div ng-controller="CartController">
<span ng-model="cid">{{cid}}</span>
</div>
Myrouting
var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: '/Product/Details',
controller: 'CartController'
});
}]);
I created a plunker for this. I am unable to send the data from page1 to page2
http://plnkr.co/edit/micM7vlslznEIZXP293Y?p=preview
Your problem is your controller is instantiated again while clicking on href and the scope is getting recreated & $scope.cid is set to undefined.
You could achieve the same by using $routeParams which will give the access to what url contains
In your case it would be $routeParams.cid
Code
app.controller('CartController', function ($scope, $routeParams) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
//$scope.cid = cartprd[len];
}
$scope.cid = $routeParams.cid;
});
Update
You should use $routeParams service to get data from url
Code
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: 'page2.html',
controller: 'CartController'
}).when('/', {
templateUrl: 'page1.html',
controller: 'CartController'
});
}
]);
app.controller('CartController', function($scope, $routeParams) {
$scope.myvar = $routeParams.cid; //this will asign value if `$routeParams` has value
console.log($scope.myvar);
$scope.Add = function(c) {
$scope.myvar = c;
}
});
Working Plunkr
I'm experimenting with $routeParams, by following along with this example in the AngularJS documentation. For reference, here is the script itself:
angular.module('ngRouteExample', ['ngRoute'])
.controller('MainController', function($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller('BookController', function($scope, $routeParams) {
$scope.name = "BookController";
$scope.params = $routeParams;
})
.controller('ChapterController', function($scope, $routeParams) {
$scope.name = "ChapterController";
$scope.params = $routeParams;
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterController'
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
What I can't understand is this: how does MainController get the updated $routeParam object? I can see that as I click, items that MainController is responsible for setting are changing, but I don't understand how. It's making it a little tough to reproduce this behavior.
It doesn't get re-instantiated, and it's not "getting" the updated $routeParams object - the object in the controller is the routeParams object. It is the same object that is in the other controllers, not a "copy" of it.
So when the $routeParams object gets changed, the other controller already has the changes.
I want to reuse link.
How to use $routeProvider and custom module in config function?
angular.module('urls', []).
factory('$urls', function (
$location
) {
var $urls = {};
$urls.login = function () {
var url = '/login';
return url;
}
return $urls;
});
angular.module('app', ['urls']).
config(function ($routeProvider, $urls) {
$routeProvider.
when($urls.login(), { controller: PageCtrl, templateUrl: 'tem.html' }).
otherwise({ redirectTo: $urls.login() });
});
As I commented you can create a provider instead of a factory and put the URLs in that as the central place:
angular.module('urls', []).
provider('urls', function (){
this.$get = function(){
var obj = {}
obj.login = function(){ return '/login';}
//more urls here, you don't really need function though
return obj;
}
});
angular.module('app', ['urls']).
config(function ($routeProvider, urlsProvider) {
$routeProvider.
when(urlsProvider.login(), { controller: PageCtrl, templateUrl: 'tem.html' }).
otherwise({ redirectTo: urlsProvider.login() });
});
However, you can not inject the $location service to the urls provider. But if you really want to use $location, you can create another service that uses both the urls service and $location service to achieve the same effect like this:
angular.module('urls', []).
service('myUrlService', function (urls, $location){
this.goToLogin = function(){$location.path(urls.login());}//just an example
});
Then you can inject myUrlService to your controllers and do things like this:
myUrlService.goToLogin();