Angular 1.3 - Error instantiating module - javascript

I am new to Angular and following a tutorial to learn the basics. Below is the code that I have so far. It has a controller and a view
// Code goes here
(function() {
var app = angular.module("myApp", []);
var MainController = function($scope) {
var person = {
var firstName = "AAA",
var lastName = "BBB",
};
$scope.person = person;
$scope.message = "Hello";
}
app.controller("MainController", MainController);
}());
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#1.3.19" data-semver="1.3.19" src="https://code.angularjs.org/1.3.19/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MainController">
<div>First Name: {{person.firstName}} </div>
</div>
</body>
</html>
It gives me the below error in console
Please let me know what I am doing incorrectly. Thanks!

The problem is in initializing person object:
var person = {
var firstName = "AAA",
var lastName = "BBB",
};
The right way to do that is:
var person = {
firstName: 'AAA',
lastName: 'BBB'
}
Hope, my answer will help you.
Thanks. : )

Related

AngularJS function not working

There are no errors or warnings. This function doesn't display the result, instead it shows as:
{{student.fullName}}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app = "mainApp" ng-controller="studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
your full name is: {{student.fullName()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Narasimha",
lastName: "Rao",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>
output:
Works like a charm
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Narasimha",
lastName: "Rao",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "mainApp" ng-controller="studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
your full name is: {{student.fullName()}}
</div>
The code is working properly. What are you using to run your file?

No Inheritance is occuring in the angularJS code

This is an AngularJS inheritance code where the inheritance is applied in the functions but there is no output coming for this code.
custDetails and empPaycheck are the two functions where inheritance is applied but the code has some error which I am not been able to find.
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Controller Inheritance</title>
<script src="angulaar.min.js"></script>
<script>
var app = angular.module("sample",
[]).run(["$rootScope",function($rootScope){
$rootScope.taxPe`enter code here`rcent = 30;
}]);
app.controller("custDetails", ["$scope",function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}]);
</script>
</head>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong>
Department.
<div controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
</html>
You should use $scope.$parent to access parent $scope variables in a child controller.
Also in your HTML code there's a typo where controller should be ng-controller.
Look at the following working example.
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.$parent.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.$parent.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div>
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
There is error in your module run block near $rootScope.taxPe;
You are using controller attribute instead of ng-controller.
Here is a working code snippet:
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
P.S.: Personally I would not recommend using $rootScope and scope inheritance, you can use services to share data between controllers. Also would suggest you looking into component API that comes in v1.5+.

AngularJS - Filter requires string despite being a string

I am getting the following error: Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html on this simple code despite its typeof() saying it is a string...
var app = angular.module('app', ['angular.filter', 'ngSanitize']);
app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.filters = {};
this.people = [{
name: 'Yasuhito Endo'
}, {
name: 'Dejan Damjanović'
}, {
name: 'Gao Lin'
}, {
name: 'Mohammed Noor'
}];
this.applyFilter = function() {
console.log('Making first names bold...');
this.people = $filter('nameBold')(this.people);
}
}]);
app.filter('nameBold', function($sce) {
return function(items) {
var filtered = [];
angular.forEach(items, function(item) {
var splitIt = item.name.split(" ");
item.name = '<strong>' + splitIt[0] + '</strong> ' + splitIt[1];
console.log('Trusting... ' + typeof(item.name));
// Trusting... string (4x) |
// OUTPUT ------------------
// It outputs as a string yet it gives me the error:
// Error: [$sce:itype] Attempted to trust a non-string value
// in a content requiring a string: Context: html
// --------------------------------
// https://docs.angularjs.org/error/$sce/itype?p0=html
filtered.push(item.name);
});
return $sce.trustAsHtml(filtered);
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script data-require="angular-filter#*" data-semver="0.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.2/angular-filter.js"></script>
<script data-require="lodash.js#*" data-semver="3.10.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as viewmodel">
<button ng-click="viewmodel.applyFilter()">Apply the Filter</button>
<div ng-repeat="person in viewmodel.people">
Person: <span ng-bind-html="person.name"></span>
</div>
</body>
</html>
Plunker snippet: http://plnkr.co/edit/rIlETpJ3GeW0YYqrc8NB?p=preview
As you can see from the code, it looks very simple yet the returned item is a string and yet it gives me that big, nasty error.
How do I fix this?
Thanks.
I figured it out. Just take what you put as variable (From object) and put it as as new variable to a string.
app.filter('nameBold', function($sce) {
return function(items) {
var filtered = [];
var itemName = "";
angular.forEach(items, function(item) {
var splitIt = item.name.split(" ");
item.name = '<strong>'+splitIt[0]+'</strong>';
itemName = item.name;
filtered.push(item.name);
});
return $sce.trustAsHtml(itemName);
};
});

How do I make a scope function work when using ng-include?

<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="keyboard.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab|Roboto' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="keyboard.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-include src="'keyboard.html'"></div>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
</script>
</body>
</html>
I know this is a bit thrown together, (the main code is just an example app from w3schools) but it shows what I am trying to do. So I have a keyboard app that I am bringing into the file (ng-include) and it appears absolutely wonderfully. My issue is that $scope is not being recognized. I have read the "Understanding Scopes" github document but it is just a bit much for me to take in. If someone could explain what I need to do to make sure that all of my $scope functions actually function, I would appreciate it greatly.
as Fissio said in the comments, you have a scope function declared outside of your controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
/**** see this here ****/
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
this is what you need:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.insertString = function(letter) {
//$scope.name = $scope.name + letter;
$scope.name = [$scope.name.slice(0,$scope.cursorPosVal),letter,$scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
};
});
you can't use the keyword $scope outside of your controller because its bound to your controller. When it's outside angular will not know what it is that's why it will say something like it's not recognized

Ember action not connecting to method

I am having a problem which should have a simple solution. For some reason my action helper is not connecting to its method.
Here is my JSBin http://jsbin.com/UMaJaM/5/edit
Code is copied below for reference.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Ember template" />
<meta charset=utf-8 />
<title>JS Bin</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.1.2/ember.js"></script>
</head>
<body>
<div id="main"></div>
</body>
</html>
JavaScript:
var TemplatedViewController = Ember.Object.extend({
templateFunction: null,
context: null,
viewBaseClass: Ember.View,
view: function () {
var controller = this;
var context = this.get('context') || {};
var args = {
template: controller.get('templateFunction'),
controller: controller
};
args = $.extend(context, args);
return this.get('viewBaseClass').extend(args);
}.property('templateFunction'),
appendView: function (selector) {
this.get('view').create().appendTo(selector);
},
appendViewToBody: function (property) {
this.get(property).create().append();
}
});
var template_source = '<button type="button" class="btn" {{action "button"}}>Click</button>';
var MyController = TemplatedViewController.extend({
templateFunction: Ember.Handlebars.compile(template_source),
button: function() {
console.log('hello world');
}
});
var controller = MyController.create();
$(function () {
controller.appendView('#main');
});
You need to create an Ember application. Add this to the beginning of your script:
App = Ember.Application.create();

Categories

Resources