Angular Js linking a controller to a route doesn' work - javascript

I watching an Angular course on codeschool and it say that there are two way to link a controller to a route
The first one is declaring the controller inside the route like this:
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller: function(){.....}
})
the second way is to create a new file and then, over there, declare all the methods associate to that controller. After this have been done, we have to associate the controller to the route, like this.
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
This controller, I've made, import some data using an ajax call from a json file but it doesn't work well. I have to use this controller inside an HTML file
this is the controller
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('notes.json').success(function(data){
controller.notes = data;
})
}]);
This is the HTML code
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
the html should import all note stored inside the controller.notes array and display all it but it seems like the html doesn't recognize the controller and does't import anything.
The code works just if I declare inside the HTMl the controller I have to use like this:
<div ng-controller="NotesIndexController as indexController">
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
My question is. If I declare the controller inside my route why I should declare it also in my HTML?

Ok thanks everybody, I figured out what was the problem. This is the complete route.js file
angular.module('NotesApp',["ngRoute"])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:'templates/pages/notes/index.html',
controller:'NotesIndexController', // I have to declare the controller inside the template to make it work
controllerAs:'indexController'
})
.when('/users',{
templateUrl: 'templates/pages/users/index.html'
})
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
.when('/notes/:id', {
templateUrl:'templates/pages/notes/show.html',
controller:'NoteShowController',
controllerAs:'showController'
})
.otherwise({redirectTo:'/'});
}]);
The problem was the line:
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
instead, to load my controller should have been
.when('/',{
redirectTo: '/notes'
})

Please find this working plunk with your code
angular.module('NotesApp', ["ngRoute"])
.config(function($routeProvider){
$routeProvider.when('/', {
templateUrl:'main.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
})
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('data.json').success(function(data){
console.log(data)
controller.notes = data;
})
}]);

Related

Can't access controller properties in view with UI router and 'controller as' syntax

I am using ui-router for my routing, and am going to be using nested scopes and therefore want to be using the 'controller as' syntax. However, I can't work out the correct syntax / combinations to access the controller object properties in my view.
app.js (sets up routing)
(function() {
angular
.module('ICP_App', ['ui.router', 'satellizer', 'ngMaterial', 'ngMessages', 'xeditable'])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$urlRouterProvider.otherwise('dashboard');
$stateProvider
.state('clients', {
url: '/clients',
templateUrl: '../partials/clients-index.html',
controller: 'ClientsController as ClientsCtrl'
})
// more routes here...
})();
ClientsController.js
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
var vm = this;
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
});
})();
index.html
<body ng-app="ICP_App" ng-cloak>
<!-- sidebar, header etc -->
<div ui-view></div> <!-- pull in view -->
</body>
Finally, clients-index.html partial
<div class="content">
<div class="pane" ng-repeat="client in clients">
{{ client.name }}
</div>
</div>
I have also tried client in vm.clients, to no avail.
Is there a problem with my controller as syntax? As I am using controller as in my ui-router code, yet not again when creating my controller. If I use controller as again in my controller, it errors (Argument ClientsController is not a).
I should point out that console logging vm.clients does give me the data in the console, I just can't seem to access it in my view.
Thanks in advance.
Modify your ClientsController as follow
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
var vm=this;
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
}); })();
Modify client-index.html as following
<div class="content">
<div class="pane" ng-repeat="client in ClientsCtrl.clients">
{{ client.name }}
</div>
Below link will help you to understand controller as syntax more deeply
https://toddmotto.com/digging-into-angulars-controller-as-syntax/

How should I get the data from JSON into another angular js controller?

I'm new to AngularJS and stuck on below code.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/home.html",
controller: "mainController",
})
.when('/products', {
templateUrl: "partials/productlist.html",
//controller: "ProductController",
})
.when('/product/:prodID', {
templateUrl: "partials/product.html",
controller: "viewController",
})
.when('/contact', {
templateUrl: "partials/contact.html",
controller: "contactController",
})
.otherwise({
redirectTo: "/"
});
});
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams){
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
And my product.html page code will look like this.
<div ng-controller="viewController">
<ol class="breadcrumb">
<li>Home</li>
<li>Products</li>
<li class="active">{{eachproduct.link}}</li>
</ol>
<div class="col-md-4">
<figure><img ng-src="{{ }}"></figure>
<p>
Read More
</p>
</div>
</div>
Problem is when I navigate to any product page value of {{eachproduct.link}} is not showing.
Any solution will be appriciated.
Use $rootScope instead of $scope
$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
Sample :
controller('viewController',['$scope','$routeParams', '$http','$rootScope',function($scope,$routeParams, $http,$rootScope){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$rootScope.eachproduct = $scope.datap[$routeParams.prodID];
});
}]);
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
});
It seems like what you are looking for is an angular provider such as a factory to store the values in, this will allow the values to be pass values around the controllers while using the routes.
Have a look at this example, while it isn't using routes, the principal is the same:
https://jsbin.com/wiwejapiku/edit?html,js,output
For more information on providers have a look here:
https://docs.angularjs.org/guide/providers
Your example would work something like this:
app
.factory('productFactory',function(){
return {
data: {}
};
})
.controller('ProductController', function($scope, $http, productFactory){
$scope.productFactory = productFactory;
$http.get('partials/productTable.json').success(function(response){
$scope.productFactory.data = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, productFactory){
$scope.productFactory = productFactory;
$scope.eachproduct = $scope.productFactory.data[$routeParams.prodID];
});
Note you would also have to change your view to reference 'productFactory.data' respectively.

Saving an object into an array in a controller in AngularJS

I've been creating a contact list website and have just begun trying to implement an add contact function. So far I have created the page using a form and input elements and then use ng-click to call a function which theoretically would add an object containing these input values into an already-existing array in the controller. For some reason this doesn't work and nothing is added.
In particular, I'm having trouble with the js/app.js file and the $scope.saveContact = function() in relation to the partial/edit.html webpage. Clicking the "Confirm button" when trying to add a contact calls the saveContact function, but the results are not stored properly. Any help is appreciated.
In my HTML I have this code (which calls the saveContact() function in my controller.
<a href="#/"><div class="confirm col-xs-6" ng-click="saveContact()">
<h3>Confirm</h3>
</div></a>
In my app.js file I have a declaration of an empty object and an array containing objects that already have values (used to display the contacts that are already created). I'm trying to add to these contacts using .push() but it for some reason it doesn't work.
$scope.contact = { ... } //empty object that gets inputs from HTML
$scope.contacts = [ { ... }, ... ];
$scope.saveContact = function(){
$scope.contacts.push($scope.contact);
};
This bottom function fails to push the contact object to the contacts array and I don't understand why.
This is happening as you have assigned same controller to all your routes. Your saveContact function is working fine, its pushing the object to the array. As soon as the route changes, a new instance of the controller is created and hence the added object is lost. You should create a service(singleton) to store the object and inject the service as a dependency to the controller. In this way the array will persist until the page load.
app.service("storeContact", function(){
var contacts = [];
this.setContact = function(cnt){
contacts.push(cnt)
};
this.getContact = function(){
return contacts;
}
});
And inject it in the controller and use the setContact and getContact methods to update the contact array and retrieve the contact array.
Ideally, you should have separate controllers for your route.
The issue is in your app.config code. You are using the same controller for all your templates.
This is not required since you have already mentioned the same in ng-controller attached with body
<body ng-controller="AppController">
<div ng-view></div>
<script src="js/app.js"></script>
</body>
Using same controller for all your routes is essentially (re)instantiating the controllers when the route is changed and thats the reason why $scope.contacts.push($scope.contact); is ineffective for the route / when called from /add.
contactListApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'AppController',
controllerAs: 'list',
templateUrl: 'partials/list.html'
})
.when('/add', {
controller: 'AppController',
controllerAs: 'add',
templateUrl: 'partials/edit.html'
})
.when('/edit/:id', {
controller: 'AppController',
controllerAs: 'edit',
templateUrl: 'partials/edit.html'
})
.otherwise({
redirectTo: '/'
});
}]);
Workaround:
Either use separate controllers for separate routes and use a service to store the object
OR
Simply remove the controller and controller as from your route config and you are good to go.
Updated config:
contactListApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/list.html'
})
.when('/add', {
templateUrl: 'partials/edit.html'
})
.when('/edit/:id', {
templateUrl: 'partials/edit.html'
})
.otherwise({
redirectTo: '/'
});
}]);

AngularJS get parameters from Laravel

I don't know how to pass a variable from home.blade.php of Laravel to my Controller.js of AngularJS.
LARAVEL:
I have a home.blade.php with a variable searchid:
#extends('layouts.default')
#section('content')
<div class="row" ng-app="app">
{{ $searchid }}
<post-controller></post-controller>
</div>
#stop
This variable is send by controller of Laravel:
class SearchController extends BaseController {
public function makeSearch($searchid)
{
return View::make('pages.search')->with('searchid', $searchid);
}
}
ANGULARJS:
I need to pass this variable to AngularJS controller.
I have a directive file like this:
app.directive('postController', function()
{
return {
restrict: 'E',
templateUrl: 'templates/search.html'
}
});
And controller file like this:
app.controller('SearchController', ['$scope', function($scope, $routeParams)
{
console.log($routeParams.search);
$scope.param = $routeParams.search;
}]);
I don't know how to pass this variable search to my controller.js.
There's a nice package that does nearly all the work for you. PHP-Vars-To-Js-Transformer
However the basic principle is just passing variables to javascript by creating a <script> tag in your view and defining javascript variables. Here's an example:
<script type="text/javascript">
var searchId = {{ $searchId }};
</script>
Attention depending on the data type of your variable you'll have to use quotes around it or maybe even serialize it with json.

AngularJS Controller depending on URL parameter

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.
I start to learn AngularJS and I have a very simple question :
Depending on ID contained in URL, I would like to display different BD record.
...
<div ng-app=MyApp>
<div ng-controller="MyCtrl">
{{ record }}
</div>
</div>
...
My Javascript file :
var MyApp = angular.module("MyApp",[]);
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/get/:productId', {
controller: 'MyCtrl'
});
}])
MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
function($scope,$routeParams,$http) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
}])
I tried to use $routeProvider and $routeParams without success.
Thank you in advance,
Bill
you need 2 things , the $routeParams injected in your controller and create a valid route with the get method
MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
function($scope,$http,$routeParams) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
};

Categories

Resources