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
Related
So I am trying to list out some data from an API call, which is JSON. I am new to Angular and JavaScript and I think the whole Async thing is messing with my logic. Sometimes when I refresh the page, it works perfectly, all the data I expect to be there is, but then the next time I refresh its gone. This seems to happen when I change something in the controller.
var app = angular.module("hasRead", ['hasRead.controllers', 'hasRead.directives', 'hasRead.services', 'hasRead.filters','ngRoute']);
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/books/:shelf", {controller: "BooksCtrl", templateUrl: "partials/books_list.html"})
.when("/recomend", {controller: "RecomendCtrl", templateUrl: "partials/recomend.html"})
.otherwise({redirectTo: "/books/read"})
}]);
controller.js
var ctrls = angular.module('hasRead.controllers', []);
ctrls.controller('AppCtrl', function ($scope) {
});
ctrls.controller('BooksCtrl', function ($scope, $book, $routeParams) {
$scope.books;
var shelf = $routeParams.list;
$book.getBooks(shelf).then( function(data) {
$scope.books = data.query.results.body.goodreadsresponse.reviews;
console.log($scope.books);
$scope.$apply;
});
});
ctrls.controller('RecomendCtrl', function ($scope) {
$scope.test = "testing";
});
HTML
<div>
<book ng-repeat="review in books.review" review-data="review"></book>
</div>
Its a fair bit of code so here is a plunkr:
https://plnkr.co/edit/l3A6QF?p=info
I didn't have the parentheses in $scope.$apply(); in the controller.
I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});
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
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
I am new to AngularJS. In my project I have a search screen when search I will get the search result in the ngGrid.
On click of any row in the grid, it should populate the details of that row in other page. Basically, I need to pass the ID of the selected record to the other page. I don't know how to handle this in AngularJS (I am using AngularJS HotTowel template) and Breeze for data access logic.
Appreciate if you could provide me link or any where it is implemented which I could refer.
You can create service and share values for instance
var myApp = angular.module('myApp', []);
myApp.factory('ShareData', function() {
var shared;
return {
setValue: function(val){
shared = val;
},
getValue: function(){
return shared;
}
});
function FirstCtrl($scope, ShareData){
ShareData.setValue(1);
}
function SecondCtrl($scope, ShareData){
$scope.data = ShareData.getValue();
}
You need $routeParams for this.
Below is an example of the routing configuration:
var app = angular.module("app", ["ngRoute"])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
controller: "HomeController",
templateUrl: "/home/main",
})
.when("/products/:category", {
controller: "ProductController",
templateUrl: "/product/index"
})
.otherwise({
redirectTo: "/"
});
}]);
Product Controller
angular.module("app")
.controller("ProductController",["$scope","$routeParams", function($scope,$routeParams){
$scope.category = $routeParams.category;
alert($scope.category);
}]);
'Main' View
<a ng-href="#/products/ladies">Ladies</a>
check this URL for more info:
https://docs.angularjs.org/api/ngRoute/service/$routeParams