Angular Factory Injection not working - angularjs

im trying to get Angular to work at a really basic level. But i just dont get it. Im doing all the tutorial and everything. It kills me.
Here is what im doing:
1.) HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/Controller.js"></script>
<script src="js/friendsFactory.js"></script>
</head>
<body>
<div ng-app="friendsApp">
<div ng-controller="friendsController">
<h3>{{girlFriendName}}</h3>
</div>
</div>
</body>
</html>
2.) App.js
var friendsApp = angular.module('friendsApp',[]);
3.) Controller.js
friendsApp.controller('friendsController', ['$scope','friendsFactory', function($scope, friendsFactory){
$scope.girlFriendName = friendsFactory.girlFriend();
}]);
4.) Friendsfactory.js
friendsApp.factory('friendsFactory', function (){
this.girlFriend = function(){
var name = "Girlfriends Name";
return name;
}
});
I wanted to try this at a very basic level but now i have spent 5 hours trying to get a name from the Factory to the Controller.
If i write the name manually into the controller it works, so the controller get called.
Can anybody tell me where i am thinking wrong here?
Thank you very much!

Modify factory code:
friendsApp.factory('friendsFactory', function (){
this.girlFriend = function(){
var name = "Girlfriends Name";
return name;
}
});
To:
friendsApp.factory('friendsFactory', function (){
function girlFriend(){
var name = "Girlfriends Name";
return name;
}
return {
girlFriend: girlFriend
}
});

You have created the factory methods but didn't return it.
friendsApp.factory('friendsFactory', function (){
this.girlFriend = function(){
var name = "Girlfriends Name";
return name;
}
return {
girlFriend : this.girlFriend
}
});

Related

Angular variable are not refreshing on page when fetching data from google script

Doing one Google Script APP. With server side method that returns array of string.
getClassRoomList().
Can you please suggest what is wrong with my current HTML? As the success handler is running all well on response. But the ng variable message is not reflecting on page; while the jQuery does populate the table.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script>
var app = angular.module('myApp',[]);
app.controller('mainCtrl',function($scope){
$scope.message = [];
$scope.populateTable = function(array){
//Setting ng variable; but the page doesn't show anything
$scope.message = array;
//Setting the Table by JQuery; it does work.
var table = $('#myTable');
table.empty();
for (var i = 0; i < array.length; i++) {
var item = '<tr><td><div class="classname">' + array[i] +'</div></td></tr>';
table.append(item);
}
};
$scope.mainClick = function(){
$scope.message = $scope.message + 'chirag';
google.script.run.withSuccessHandler($scope.populateTable).getClassRoomList();
};
});
</script>
</head>
<body ng-controller="mainCtrl">
<button ng-click="mainClick()">Proceed</button>
<table id="myTable"></table>
<div ng-bind="message"></div>
</body>
</html>
This works. Thanks. google.script.run.withSuccessHandler((e) => {$scope.populateTable(e); $scope.$apply();}).getClassRoomList();

Adding object to model, doesn't update dom

I have a method that creates an object and pushes it to an array
$scope.contracts = [];
$scope.addContract = function () {
var contract = {
...
}
$scope.contracts.push(contract);
console.log($scope.contracts);
}
now in my DOM, i have the following (merely for debugging)
{{contracts}}
But this doesn't update. I validate in the console, that the object is in the array.
Why doesn't the model update?
I've already tried various applications of $scope.$apply, but they all result in an
$apply already in progress
Something must be wrong with your code, check your DOM. Does anything happen when you call your function? Heres is a working example:
var app = angular.module("myApp",[]);
app.controller("test", function($scope){
$scope.contracts = [];
$scope.addContract = function () {
var contract = {
"con":"tract"
}
$scope.contracts.push(contract);
console.log($scope.contracts);
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="test">
{{contracts}}
<button ng-click="addContract()">Add contract</button>
</body>
</html>

Unable to get data from promise to view

I was using google calendar api in angularjs and was trying to access the data in promise but i find the data is not accessible in view can you just check and let me know where i am going wrong.
<!DOCTYPE html>
<html>
<head>
<title>Google Cal Test</title>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyCtrl">
Hello<span ng-bind="responsevalue"></span>
</div>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script>
angular.module('MyApp',[])
.factory('gapi',function($window){
return $window.gapi;
})
.controller('MyCtrl',['$scope','gapi','$q',myCtrl])
function myCtrl($scope,gapi,$q){
var vm = this;
var CLIENT_ID = 'CLIENT_ID HERE PLZ';
var SCOPES = ["https://www.googleapis.com/auth/calendar"]
console.log(gapi);
data = {
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': false
};
gapi.auth.authorize(data)
.then(function(authResult){
console.log(authResult);
if(authResult && !authResult.error) return gapi.client.load('calendar', 'v3')
})
.then(function(){
return gapi.client.calendar.calendarList.list()
})
.then(function(resp){
console.log(resp);
$scope.responsevalue = resp;
console.log($scope.responsevalue);
})
}
</script>
</body>
<html>
If i am doing anything wrong please let me know or if the code can be improved better way also do let me know.

Problems relate to directive in angular JS

I am new to Angular Js and i have just done basic tags of angularjs,controller and when i started directive part i understood the concept but was unable to fetch data input written in template which is one of the directive property..Please guide me so that i can take one step further in AngularJS.
Thanks in Advance!!
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="appname" directive-name></div>
<script>
var app = angular.module("appname",[]);
app.directive("directiveName",function()
{
return
{
template : "Hi i am template"
};
});
</script>
</body>
</html>
Nothing wrong with your logic or Angular, it's because of JavaScript automatic semicolon insertion. Lines that do not end with a semicolon, but could be the end of a statement are automatically terminated. So, your return statement -
app.directive("directiveName",function()
{
return //automatic semicolon insertion here
{
template : "Hi i am template"
};
});
Should be indeed -
app.directive("directiveName",function()
{
return{
template : "Hi i am template"
};
});
Your close:
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="appname" ng-controller="MyController">
<h1>{{Header}}</h1>
<my-template></my-template>
<script>
var app = angular.module("appname",[]);
app.controller("MyController", function ($scope){
$scope.Header = "My Directive";
});
app.directive("myTemplate",function() {
return {
template : "<span>Hi i am template</span>",
restrict: 'E',
};
});
</script>
</body>
</html>
I've tested the above code and will render your directive.
everything is allright, except the linebreak after the return.
return {
template : "Hi i am template"
};
There are many problems:
1. You should use https for cdn
2. You have to put var app = angular.module("appname",[]); before the ng-app tag
the return should be
return { //the brace should be after return
template : "Hi i am template"
};
because in modern browsers semicolons are not mandatory(they are added automatically), so return means returns nothing.
finally:
<script>
var app = angular.module("appname",[]);
app.directive("directiveName",function()
{
return{
template : "Hi i am template"
};
});
</script>

How to set first item as default select

I am new to angular.js. I am using list of users with sorter list, when I click the user name the selected user phone number should display in the selected area. It is working fine.
My question is how to I set the first user as default select. here is my sample code. Please help me on this.
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="js/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Selected View</h1>
<ul>
<li ng-repeat="userNames in users | orderBy:orderProp:direction" ng:click="select(userNames)">{{userNames.name}}</li>
</ul>
<p>selected: {{selectedUser.phone}}</p>
<script>
var myApp = angular.module('myApp', []);
//myApp.by.id('setbtn')element('h1').addClass('active');
myApp.controller('MainCtrl', ['$scope', function ($scope) {
$scope.users = [{name:'John', phone:'555-1276'},
{name:'John', phone:'555-1278'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}];
//sorting
$scope.direction = false;
$scope.orderProp = "name";
$scope.sort = function(column) {
if ($scope.orderProp === column) {
$scope.direction = !$scope.direction;
} else {
$scope.orderProp = column;
$scope.direction = false;
}
};
//selected list
$scope.select = function(phone) {
$scope.selectedUser = phone;
};
}]);
</script>
</body>
</html>
Just use this in the controller to sets the default user's phone number
$scope.selectedUser = $scope.users[0];
Since the users in a JS Object, instead of a native datatype, the initial selection often causes a problem.
You'll be better off to refactor the select options to use an array of strings rather than an array of Objects.
It is covered in detail in this post.
Hope this helps!
You can sort users from controller instead of html
HTML
<li ng-repeat="userNames in getSortedUsers()"
ng:click="select(userNames)">{{userNames.name}}</li>
Controller
$scope.getSortedUsers = function () {
// Use $filter service. You have to add $filter as dependencies in controller
var users = $filter('orderBy')($scope.users, $scope.orderProp +
':' + $scope.direction);
// Set first user as selected user
$scope.selectedUser = users[0];
return users;
}

Resources