I'm trying to link to a different page/view via ng-click and a function inside my controller. I don't do it with href because later it should be a right-click-event. But my code doesn't work. I've tried very much, and searched alot of pages but I can't find any solution. Thanks for your help :)
game.html
<div class="container" ng-controller="MainController">
<div class="handcards" ng-repeat="card in stdCards">
<a ng-click="goToCardDetail()" href="">{{ card.name }}</a>
</div>
</div>
MainController.js
app.controller('MainController', ['$scope', 'stdcards', '$location', function($scope, stdcards, $location) {
stdcards.success(function(data) {
$scope.stdCards = data;
});
$scope.goToCardDetail = function() {
$location.path('#/cards/0');
};
}]);
app.js
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainController',
templateUrl: 'templates/game.html'
})
.when('/cards/:id', {
controller: 'CardController',
templateUrl: 'templates/card.html'
})
.otherwise({
redirectTo: '/'
});
});
You don't need to include the # when you are calling $location.path(). So it should just be
$location.path('/cards/0');
Related
I am trying to figure out how to build a SPA with angularjs. My routes are working and each partial page is loading in ng-view properly. I'm trying to load external json data. I had it working onnce but I can't figure out what I'm doing wrong. The goal is to list products and have a details page for each product. Any help would be greatly appreciated. Here's my code:
app.js
var myApp = angular.module('app', ['ngRoute']);
myApp.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$routeProvider.
when('/home',{
templateUrl: 'partials/home.html',
controller: "storeCtrl"
}).
when('/about',{
templateUrl: 'partials/about.html',
controller: "storeCtrl"
}).
when('/computers',{
templateUrl: 'partials/computers.html',
controller: "storeCtrl"
}).
when('/smartphones',{
templateUrl: 'partials/smartphones.html',
controller: "storeCtrl"
}).
when('/tablets',{
templateUrl: 'partials/tablets.html',
controller: "storeCtrl"
}).
otherwise({
redirectTo: '/home'
});
}]);
myApp.controller('storeCtrl', ['$scope', '$http', function($scope, $http) {
$scope.homeHeading = 'Home';
$scope.aboutHeading = 'About Us';
$scope.computersHeading = 'Computers';
$scope.smartphonesHeading = 'Smartphones';
$scope.tabletsHeading = 'Tablets';
$http.get('products.json').success(function(data) {
$scope.products = data;
});
console.log($scope.products);
}]);
computers.html
<div ng-controller="storeCtrl">
<h1>{{computersHeading}}</h1>
<div ng-repeat="item in products">
<p>{{ item.name }}</p>
</div>
</div>
You should try this
$http.get('products.json').then(function(result) {
$scope.products = result.data;
});
And remove ng-controller from the view as you have already defined it in myApp.config()
Try to use $http.get service which returns a promise object.
I have basic routing working, but when I try and include params in my routes, nothing renders inside my ngview
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/second/:num', {
templateUrl: 'pages/second.html',
controller: 'mainController'
})
});
myApp.controller('mainController',
['$scope', '$log', '$routeParams', function($scope, $log, $routeParams) {
$scope.name = "Chris";
alert($routeParams);
$scope.num = $routeParams.num;
$log.info($scope.num)
}]);
So when I try and access /second/:num nothing renders in my ngview. But if i do / or /second, those pages work properly
Hey you please check the controller in second.html page whether the controller is added or not and i suggest always use different controllers for each template.
Best way is use stateProvider easy and flexible than routeProvider both are same but stateProvider is more handy.
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($stateProvider) {
$stateProvider
.state('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.state('/second/:num', {
templateUrl: 'pages/second.html',
controller: 'mainController'
})
});
myApp.controller('mainController', ['$scope', '$log', '$stateParams', function($scope, $log, $stateParams) {
$scope.name = "Chris";
alert($stateParams);
$scope.num = $stateParams.num;
$log.info($scope.num)
}]);
There must be something in the way you are declaring the path to your templates, or some kind of error in your console. Below is a repro of your code, with the html files in ng-templates:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/second/:num', {
templateUrl: 'second.html',
controller: 'mainController'
})
});
myApp.controller('mainController', ['$scope', '$location', '$log', '$route', '$routeParams', function($scope, $location, $log, $route, $routeParams) {
$scope.name = "Chris";
$scope.num = $routeParams.num || 'not defined';
console.log($scope.num);
$scope.goTo = function(number) {
$location.path('/second/' + number);
};
$scope.route = $route.current;
$scope.goHome = function(number) {
$location.path('/');
};
}]);
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script data-require="angular-route#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
</head>
<body ng-controller="mainController">
<div ng-view></div>
<script type="text/ng-template" id="main.html">
<pre>route params: {{route.params}}</pre>
This is the main page, where $scope.num is {{ num }}
<ul>
<li ng-repeat="num in [0,1,2,3, 'zebra']">
<button ng-click="goTo(num)">{{ num }}</button>
</li>
</ul>
</script>
<script type="text/ng-template" id="second.html">
<pre>route params: {{route.params}}</pre>
This is the second page, where $scope.num is {{ num }}
<br>
<button ng-click="goHome()">Home</button>
</script>
</body>
</html>
Does anything jump out at you?
Inside the controller I have a login() function which should be called using ng-click like this:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
MainJS:
angular.module('angularoauthexampleApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/afterlogin', {
templateUrl: 'views/afterlogin.html',
controller: 'AboutCtrl'
})
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, $rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken = params;
}
$location.path("/afterlogin");
}
})
.otherwise({
redirectTo: '/'
});
});
Controller:
angular.module('angularoauthexampleApp')
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.login=function() {
alert("main");
var client_id="343625411797-hcm0impil8l1mughb8ma2jj966um05bp.apps.googleusercontent.com";
var scope="email";
var redirect_uri="http://localhost:9046/RTH_Sample4/app/";
var response_type="token";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
}]);
Nothing happens when I click the button on the form or event is not getting fired. I can't see anything wrong with code but some how its not working
MainCtrl gets loaded inside the views/main.html
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
this has to be loaded inside a ng-view directive in your root html.
Inside that html you can use the login().
Another way is to directly use the controller in the root html:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons" ng-controller="MainCtrl">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
Also, you have attached ng-click to the i element so you have to click the G icon for login() to work. Move it to the a element and you should be ok.
I have the following div in my index.html, whose controller is MainCtrl. This is the div used to load views from different controllers.
<div ng-controller="MainCtrl">
<div ng-view></div>
</div>
And these are my controllers:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
}).
when('/about', {
templateUrl: 'views/about.html',
controller: 'MainCtrl'
}).
when('/services', {
templateUrl: 'views/services.html',
controller: 'ServicesCtrl'
}).
when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
}).
otherwise({redirectTo: '/main'})
}])
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('data/services.json').then(function(response){
$scope.services = response.data;
});
}])
.controller('ServicesCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('data/services.json').then(function(response){
$scope.services = response.data;
});
}])
.controller('ContactCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('data/locations.json').then(function(response){
$scope.locations = response.data;
});
}]);
It all works fine, but I do not understand how do all the views from different controllers get loaded automatically inside the <div ng-controller="MainCtrl"> ?
So for example if I go to mysite/services, it loads services.html, even though its controller is ServicesCtrl.
It seems logical to me that it should only load the view from MainCtrl, which is main.html and about.html, yet it loads them all irrespective of controller names, how come?
There shouldn't be an ng-controller="MainCtrl" because the controllers for each route are defined in your routing configuration.
If you have this in your page then when about or main load you will actually initialize 2 instances of MainCtrl. One instance will be invoked by the router and the other by ng-controller and this can be problematic.
That being said you could have an outer controller but it wouldn't be the same as the ones used in the routes
I have something like that in my code
<ul ng-model="services">
<p ng-repeat="item in items"><b>{{ item.name }}</b>
</p>
I have for example 3 items: BMW, golf and mercedes
I want to have an url with the name of each item, like /bmw or /mercedes and all url use details.html to show the details of the selected Item.
I'm trying to understand how can I do this.
You can write a generic route like
.when('/car/:carId', {
templateUrl: 'some/path/details.html',
controller: 'someCtrl'
})
And then in the controller you can get the value of :carId using the $routeParams
You just need to code this :
<ul ng-model="services">
<p ng-repeat="item in items"><a href="/items/{{item}}">{{ item.name }}</b>
</p>
</ul>
And then capture the url in your app.js just like below:
.when('/item/:itemName', {
templateUrl: 'some/path/itemDetail.html',
controller: 'ItemCtrl'
})
And then to finish, you just need to get the item name in your controller
ItemCtrl.js :
App.controller('ItemCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.itemName = $routeParams.itemName;
}]);
You can define paths within your module like so:
var myModule = angular.module('myModule', [])
.config(['$routeProvider', '$httpProvider', '$locationProvider', '$mdThemingProvider',
function ($routeProvider, $httpProvider, $locationProvider, $mdThemingProvider) {
$routeProvider
.when('/page1', {
templateUrl: "Views/Angular/Pages/page1.html",
contoller: "page1Ctrl"
})
.when('/page2', {
templateUrl: "Views/Angular/Pages/page2.html",
controller: "page2Ctrl"
})
.otherwise({ redirectTo: '/default' });
When the path is changed to 'page1' this module will load page1.html as the new view.
You can set up a view in an element such as:
<md-content ng-view=""></md-content>