First Angular app not outputting from controller - angularjs

I'm still very new at this and this is my first attempt to making an app without following any guide. For some reason my output in the webpage is {{$scope.products}} instead of the actual values. Can anyone tell my why it won't load the angular code from the controller?
index.html
<<!doctype html ng-app="MyFirstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainController as ctrl">
{{ctrl.name}}
{{"Hello World"}}
</body>
</html>
app.js
var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe";
});

Your snippet contains some errors:
<!doctype html ng-app="MyFirstApp"> : ngApp directive is too high. Please put it in the <body> tag at least.
ng-controller="MainController as ctrl": if it is your very first AJS example, be aware that controllerAs is a best practice, but a bit advanced. This choice will condition slightly the controller code.
{{products.title}}: products is an array!
... .controller('MainController',[$scope function($scope){: the second argument of controller method is an array, so between $scope and function a comma is needed. In your case the array must be: ['$scope',function($scope){...}]. For more info pls see https://docs.angularjs.org/guide/di
$scope.products = [...]; : in order to avoid controllerAs antipattern you must use this.products.
Please update your code.

you need to put the dependancy to your controller between '' and
you are missing some thing after $scope
.controller('MainController',['$scope',function($scope){
}]);
and there are no iterate for the array in your controller to be bind in html

var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe"
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyFirstApp" ng-controller="MainController as ctrl">
{{ctrl.name}}
</div>
AngularJS documentation can be quite confusing.
Assigning values to the $scope is considered a bad practice. This is one of the things that the controllerAs syntax solves. So instead of adding the products to $scope.products -- add them to this.name.
Then in your view you will access them with {{ctrl.name}}
I hope this helps.

Related

Unable to execute a custom directive in angularjs

I am trying to build a simple custom directive, but it is constantly throwing me an error. I have included my sample code in the below jsFiddle link. Can anyone help me with where exactly I went wrong.
[https://jsfiddle.net/sridharspeaks/65vnj4dz/][1]
Thanks,
Sridhar
this is fixed plunker :
http://plnkr.co/edit/KTFFLc0QdmunQ4i8AT8o?p=preview
i think there is a problem with
the case of your directive and controller name ( i put all to lower case, don't have too much time sorry)
you didn't use ng-controller="mycontainercontroller" to tell angular with controller to use
don't inject $scope on directive only in controller's directive :
html :
<head>
<script src="http://code.angularjs.org/1.2.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="mycontainercontroller">
<mycontainer></mycontainer>
</div>
</body>
and JS :
angular.module('myApp', []).
directive('mycontainer', function() {
return {
restrict: 'E',
scope: {},
controller: 'mycontainercontroller',
template: '<div><input ng-model="container"></div><div>output : {{container}}</div>'
}
}).controller('mycontainercontroller', ['$scope', function($scope) {
$scope.container = 123;
}]) ;
There are two issues. One is with the fiddle, the script must run before window load, so set the following:
Second, don't inject $scope into the directive. You only have access to the directive scope in the link function.
Updated fiddle: https://jsfiddle.net/65vnj4dz/5/

Directive not working in angularjs

I am newbie to Angularjs. I am trying to create simple directive with the following code:
View:
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<user-info></user-info>
</div>
</body>
</html>
Controller:
myapp = angular.module("myapp", []);
myapp.directive('userInfo', function() {
var directive = {};
directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = "My first directive: ";
return directive;
});
I am following this Tutorial to learn directive
http://tutorials.jenkov.com/angularjs/custom-directives.html
I am getting error:
http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.3.14%2F%24injector%2Fnomod%3Fp0%3DmyApp%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A6%3A417%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A412%0A%20%20%20%20at%20a%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A53)%0A%20%20%20%20at%20w.bootstrap%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A296)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A35%3A46%0A%20%20%20%20at%20s%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A7%3A302)%0A%20%20%20%20at%20g%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A34%3A399)%0A%20%20%20%20at%20ab%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A38%3A135)%0A%20%20%20%20at%20d%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381
Here is my codepen link
http://codepen.io/anon/pen/NGNKxz
You have error in the name of your app :
myapp = angular.module("myApp", []); // not 'myapp'
Add Your Directive
You need to add the directive to your html like so
<script src="path/to/your/directive.js"></script>
or if your working from one module you will link to the main module. But please restructure your app like this it will keep code up to standard and clean.
I have a git hub repo where I am building an app in this structure here. Best of luck.
Note
You are using angular min. Min is great for production because its small and faster to load but your in development at the moment so use the full version so you can capture errors better with the browser console.
Looks like you did not declare the controller myCtrl. Your directive looks fine.
myapp.controller('myCtrl', function() {
});
Is it the current version of your html file ?
Because you might need to link your controller, between head tags, insert :
<script src="the js file which contains your controller"></script>
or
<script>Your controller</script>

Angular Scope Directives

Angular Structural Question
I am new to angular.js and am just wondering how to go about performing a certain situation.
So basically, what I have got is a container:
<div ng-controller="ContainerController">
<container></container>
</div>
And the container controller and directives.
<script type="text/javascript" src="ContainerController.js"></script>
<script type="text/javascript" src="ContainerDirectives.js"></script>
Now the directives replaces the <container> tag with an example html: <example>{{ data }}</example>
Now within the scope of the ContainerController I have defined data as a string. (This is all example purposes). However when the directive accesses replaces it, it is unable to find the variable, due to scope.
The reason that this happens is because the ContainerDirective script's scope is not within the ContainerController scope. Meaning it is unable to access the variable.
Im just not sure on structure practices for these kinds of situations. Where do I put everything so the ContainerDirective can access the ContainerController scope.
I hope i have explained everything good enough
EDIT:
Test.js
(function(){
angular.module('test', []);
})();
TestController.js
(function(){
angular
.module('test')
.controller('TestController', [
'$scope',
TestController
]);
function TestController($scope) {
$scope.test = 'test';
}
})();
TestDirective.js
(function(){
angular.module('test').directive('test', function () {
return {
replace: true,
templateUrl: 'src/test/view/test.html',
link: function (scope, element, attrs) {
}
};
});
})();
test.html
<example>ClickMe</example>
index.html - body
<body ng-app="App" layout="row" ng-controller="TestController as page">
<test></test>
<script src="src/test/Test.js"></script>
<script src="src/test/TestController.js"></script>
<script src="src/test/TestDirective.js"></script>
<script type="text/javascript">
angular
.module('App', ['test']);
</script>
</body>
For reasons I have renamed certain variables and deleted a lot of data, but this is the core, and I am struggling to see anything wrong with this.
Error: [$interpolate:noconcat] Error while interpolating: abc/{{test}}
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.
So I figured out what was wrong in the end. Basically angular wont allow iframe of another location to be printed unless you first:
Give them the full url.
Then allow external url as a trusted website.
TO do this I had to basically add:
in the Test.js
angular.module('test', []).config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist($sceDelegateProvider.resourceUrlWhitelist().concat([
'http://www.test.com/**'
]));
});
This basically took my whitelist and concatinated the new url to it.
Then inside test.html:
<example><iframe ng-src={{src}}></iframe></example>

Error injecting custom service into another custom service

Now that I have my script files referenced in my view template, I am having trouble injecting the first one into the second one.
If I unplumb the dependency that LearnerService has on SCORMService, everything displays according to plan, but is of course nonfunctional because LearnerService relies on SCORMService to accomplish its purpose. When I try to actually use my SCORMService within my LearnerService, I get Michael Bay explosions and sad trombones.
So, I'm using ngRoute. That might be important; maybe not.
I'll list my app.js, my script ordering in index.html, learnerServices.js, SCORMServices.js, and controllers.js
app.js
'use strict';
var app = angular.module('client', [
'ngRoute'
,'controllers'
,'services.proxy.scorm'
,'services.proxy.lms'
]);
index.html
...
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/SCORMService.js"></script>
<script src="js/LearnerServices.js"></script>
</head>
<body>
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
LearnerServices.js
'use strict';
var learnerServices = angular.module('services.proxy.lms',['scorm-service']);
learnerServices.factory('LearnerService', [ 'scorm-service', function(){
return true;
}]);
SCORMService.js
'use strict';
var services = angular.module('services.proxy.scorm', []);
services.factory('scorm-service',function(){
var foo = {};
foo.bar = "snazzy jazzy";
return foo;
});
I seem to be attempting to corner the market on stupid mistakes today. Can anyone see what stupid mistake I did this time?
This line should be:
var learnerServices = angular.module('services.proxy.lms',['services.proxy.scorm']);
Notice in your code you are saying the module has a dependency on scorm-service however the dependency for the module is on services.proxy.scorm
Load your dependencies first in your html. That'll help.

How to access cookies in AngularJS?

What's the AngularJS way to access cookies? I've seen references to both a service and a module for cookies, but no examples.
Is there, or is there not an AngularJS canonical approach?
This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).
One other note and that is that there is a slight difference between the two when pulling data out depending on if you used $cookie to store value or $cookieStore. Of course, you'd really want to use one or the other.
In addition to adding reference to the js file you need to inject ngCookies into your app definition such as:
angular.module('myApp', ['ngCookies']);
you should then be good to go.
Here is a functional minimal example, where I show that cookieStore is a thin wrapper around cookies:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">
<h3>Cookies</h3>
<pre>{{usingCookies|json}}</pre>
<h3>Cookie Store</h3>
<pre>{{usingCookieStore|json}}</pre>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
app.controller('MyController',['$scope','$cookies','$cookieStore',
function($scope,$cookies,$cookieStore) {
var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};
$cookies.dotobject = someSessionObj;
$scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };
$cookieStore.put('obj', someSessionObj);
$scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
}
</script>
</body>
</html>
The steps are:
include angular.js
include angular-cookies.js
inject ngCookies into your app module (and make sure you reference that module in the ng-app attribute)
add a $cookies or $cookieStore parameter to the controller
access the cookie as a member variable using the dot (.) operator
-- OR --
access cookieStore using put/get methods
This is how you can set and get cookie values. This is what I was originally looking for when I found this question.
Note we use $cookieStore instead of $cookies
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
function CookieCtrl($scope, $cookieStore) {
$scope.lastVal = $cookieStore.get('tab');
$scope.changeTab = function(tabName){
$scope.lastVal = tabName;
$cookieStore.put('tab', tabName);
};
}
</script>
</head>
<body ng-controller="CookieCtrl">
<!-- ... -->
</body>
</html>
Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:
$cookies.put("key", "value");
var value = $cookies.get("key");
See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).
Note that, in version 1.3.x or below, $cookies has a different syntax than above:
$cookies.key = "value";
var value = $cookies.value;
Also if you are using bower, make sure to type your package name correctly:
bower install angular-cookies#X.Y.Z
where X.Y.Z is the AngularJS version you are running.
There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.
FYI, I put together a JSFiddle of this using the $cookieStore, two controllers, a $rootScope, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...
The gist of it is:
Javascript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
$scope.bump = function () {
var lastVal = $cookieStore.get('lastValue');
if (!lastVal) {
$rootScope.lastVal = 1;
} else {
$rootScope.lastVal = lastVal + 1;
}
$cookieStore.put('lastValue', $rootScope.lastVal);
}
});
myApp.controller('ShowerCtrl', function () {
});
HTML
<div ng-app="myApp">
<div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
<div id="button-holder" ng-controller="CookieCtrl">
<button ng-click="bump()">Bump!</button>
</div>
</div>
http://docs.angularjs.org/api/ngCookies.$cookieStore
Make sure you include http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js to use it.
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.
We need to add angular-cookies.min.js file to use cookie feature.
Here is some method of AngularJS Cookie.
get(key); // This method returns the value of given cookie key.
getObject(key); //This method returns the deserialized value of given
cookie key.
getAll(); //This method returns a key value object with all the
cookies.
put(key, value, [options]); //This method sets a value for given
cookie key.
remove(key, [options]); //This method remove given cookie.
Example
Html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);
I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.
The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.
Now, if you want to integrate js-cookie with angular, it is as easy as something like:
module.factory( "cookies", function() {
return Cookies.noConflict();
});
And that's it. No jQuery. No ngCookies.
You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:
module.factory( "phpCookies", function() {
return Cookies
.noConflict()
.withConverter(function( value, name ) {
return value
// Decode all characters according to the "encodeURIComponent" spec
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
// Decode the plus sign to spaces
.replace(/\+/g, ' ')
});
});
The usage for a custom Provider would be something like this:
module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
this.storeData = function( data ) {
phpCookies.set( "data", data );
};
this.containsStoredData = function() {
return phpCookies.get( "data" );
}
}]);
I hope this helps anyone.
See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103
For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md
Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.
app.html:
<html ng-app="app">
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="appController as vm">
<input type="text" ng-model="vm.food" placeholder="Enter food" />
<p>My favorite food is {{vm.food}}.</p>
<p>Open new window, then press Back button.</p>
<button ng-click="vm.openUrl()">Open</button>
</body>
</html>
app.js:
(function () {
"use strict";
angular.module('app', ['ngCookies'])
.controller('appController', ['$cookies', '$window', function ($cookies, $window) {
var vm = this;
//get cookie
vm.food = $cookies.get('myFavorite');
vm.openUrl = function () {
//save cookie
$cookies.put('myFavorite', vm.food);
$window.open("http://www.google.com", "_self");
};
}]);
})();

Resources