Angular - Controller as vm - javascript

Trying to get into the habit of using the controller as syntax, but seem to be missing something when trying out a simple example.
When trying to set a property like vm.name = 'John' it does not show up in my view when using {{vm.name}}.
Code is like so
controller
(function() {
'use strict';
angular
.module('myApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['dataService'];
function HomeController(dataService) {
var vm = this;
vm.data = {};
vm.name = 'Richard';
}
routes
'use strict';
angular
.module('myApp')
.config(function($routeProvider) {
$routeProvider.when(
'/view1',
{
templateUrl: 'partials/partial1.html',
controller: 'HomeController',
controllerAs: 'vm'
});
$routeProvider.when(
'/view2',
{
templateUrl: 'partials/partial2.html'
});
$routeProvider.otherwise(
{
redirectTo: '/view1'
});
});
view
<p>View 1</p>
<h1>Hello {{ vm.name }}</h1>

Not sure if you are using angular version more than 1.3, here is the working Plunker
Your HomeController should be changed like this,
app.controller("HomeController", function(){
this.name="Richard";
});

Use $scope. I think it will work. Write your code:
function HomeController(dataService) {
var vm = this;
vm.data = {};
vm.name = 'Richard';}
using $scope, try this one:
function HomeController($scope, dataService) {
$scope.data = {};
$scope.name = 'Richard';}
view
<p>View 1</p>
<h1>Hello {{name}}</h1>
Please read this article too!!!

You need to declare variables on the $scope object to achieve two way bindings. Otherwise its just a regular javascript variables. The scope is like a glue between your view and controller in angularjs.Read Here.

The only thing I can see as an issue is that you dont have ngRoute module included...
var app = angular.module('plunker', [
'ngRoute'
]);
or your dataservice isnt included as a script which is making the injection fail. Based off the information you have included I created a working plunkr for you using the view-model concept instead of $scope.
Heres angulars best practices which has some very useful information and examples on using the view-model concept, accompanied by a lot of other information Angular Guide

Related

AngularJS works once then no longer renders

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.

Defining angular controllers and component

I'm trying to call a function from within one angular component's controller to another component's controller. I found this answer, but the controllers are defined differently than what is shown in the tutorials I followed, so I'm confused as to how I'm supposed to reference the components and templates.
Here is how I currently define one of my controllers based on the official angular tutorial
angular.
module('moduleName').
component('firstComponent', {
templateUrl: 'url/to/template',
controller: function FirstController($scope) {
//I want to call a function in SecondController here
}
});
//in another component file
angular.
module('moduleName').
component('secondComponent', {
templateUrl: 'url/to/template',
controller: function SecondController($scope) {
//function here which will be called
}
});
Say I re-structure them like in the example I linked above...
var app= angular.module("myApp",[]);
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
//in another file
var app= angular.module("myApp",[]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
How am I supposed to reference each controller's component which they belong to, and their respective templates? I tried to write them like in the example I linked above, but nothing happened. I didn't get any errors, but literally nothing happened. Nothing was displayed on the page. It tried to write to the console, but nothing appeared.
Your second block of code has the right concept, but both controllers need to be instantiated for it to work.
Here's a working JSFiddle. https://jsfiddle.net/reid_horton/rctx6o1g/
When you click the button, the text Hello from callerComponent! appears below it.
HTML
<div ng-app="myApp">
<caller-component></caller-component>
<callee-component><</callee-component>
</div>
JS
var app = angular.module("myApp", []);
app.component("callerComponent", {
template: "<button ng-click='externalCall()'>Click Me!</button>",
controller: function ($scope, $rootScope) {
$scope.externalCall = function () {
$rootScope.$emit("setText");
}
}
});
app.component("calleeComponent", {
template: "<p>{{ myText }}</p>",
controller: function ($scope, $rootScope) {
$rootScope.$on("setText", function () {
$scope.myText = "Hello from callerComponent!"
});
}
});

AngularJs directive not working/visible

I'm just getting started with AngularJs. And I'm trying to implement a login directive. But I don't see the output? I've no errors in my console.
My application structure:
(index.html is not visible)
login.directive.js :
(function() {
'use strict';
angular
.module('lnjapp.login',[])
.directive('login', login);
function login() {
var directive = {
template: '<p>test</p>',
//restrict: 'E',
Controller: LoginController,
controllerAs: 'vm'
};
return directive;
}
})();
app.js :
(function () {
'use strict';
angular.module('lnjapp', ['ngRoute', 'ngCookies', 'angular.filter','lnjapp.login','lnjapp.config'])
.constant('GLOBALS', {
url:'http://domain.dev/api/v1/'
});
$(document).ready(function() {
$.material.init();
});
})();
app/pages/login.html:
<login></login>
--EDIT--
login.controller.js:
(function() {
'use strict';
angular.module('lnjapp.login',[])
.controller('LoginController', LoginController);
function LoginController()
{}
})();
route-config.js:
angular
.module('lnjapp.config',[])
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/app/pages/login.html'
});
}
What am I doing wrong here?
You are creating your lnjapp.login twice, once in login.directive.js and again in login.controller.js. The second time the module is created, it overwrites the first, and whatever was created in the first file will no longer be accessible.
You should always only create a module once, and get the already created module to add additional features in all other cases.
Set (create): angular.module('lnjapp.login',[])
Get (consume): angular.module('lnjapp.login')
For more info and other best practices, see John Papa's excellent Angular Style Guide.

Multiple Controllers for one view angularjs

I would like to know if it is possible to use multiple controllers for a single url view using angluarjs, I have not been able to find much documentation on this. I would like to use a controller on all pages to switch the page header title, but some pages already contain a controller
app.js
subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).
//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).
when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);
EDIT
I am trying to add a title controller to each page view:
function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }
If I add this controllers to the pages that don't already have a controller it works, if there is another controller in place I can't make this work.
<h1 ng-bind="header"></h1>
Yes, controllers and templates are independent, check this http://jsbin.com/wijokuca/1/
var app = angular.module("App", ['ngRoute']);
app.config( function ( $routeProvider ) {
$routeProvider
.when('/a', {templateUrl: 'this.html', controller: "aCtrl"})
.when('/b', {templateUrl: 'this.html', controller: "bCtrl"})
.when('/c', {templateUrl: 'that.html', controller: "bCtrl"})
.otherwise({redirectTo: '/a'});
});
app.controller('aCtrl', function ($scope) {
$scope.all = [1,2,3];
});
app.controller('bCtrl', function ($scope) {
$scope.all = [4,5,6];
});

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