Adding object to model, doesn't update dom - angularjs

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>

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();

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.

Angular: Setting default value in a dropdown

I have set up a plunker with basically below code.
I am unable to see the default value [Bank Account Number] getting selected in the drop down. I see that model is getting updated. But for some reasons, my default value do not get chosen. Can someone help me?
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
<script src="script.js"></script>
<script src="services.js"></script>
</head>
<body ng-controller="homeCtrl">
<h1>Other Criteria: {{ otherCriteria.optionText }}</h1>
<div>
<select data-ng-model="otherCriteria"
data-ng-options="o as o.optionText for o in criteria">
</select>
</div>
</body>
</html>
//services.js
app.factory("homeService", [
"$q",
function($q) {
function _getDropdownValues() {
var deferred = $q.defer();
var dropdownValues = [{"optionValue":"Bank_Account_Number","optionText":"Bank Account Number","selected":false},{"optionValue":"Bank_Security_Number","optionText":"Bank Security Number","selected":false},{"optionValue":"Cusip","optionText":"Cusip","selected":false},{"optionValue":"Transaction_Description","optionText":"Description","selected":false}];
deferred.resolve(dropdownValues);
return deferred.promise;
}
return {
getDropdownValues: _getDropdownValues
}
}
]);
//script.js
var app = angular.module("app", []);
app.controller("homeCtrl", function($scope, homeService) {
$scope.otherCriteria = {
optionValue: "Bank_Account_Number",
optionText: "Bank Account Number",
selected: false
};
homeService.getDropdownValues()
.then(function(dropdownValues) {
$scope.criteria = dropdownValues;
})
});
Try this plunker.
It's always a better idea to reference a default value via the index of the collection (however you want to reference it)
$scope.criteria = dropdownValues;
$scope.otherCriteria = $scope.criteria[0];
You can find more information here
Basically: Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not

Angular Factory Injection not working

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
}
});

Template preparation in AngularJs

Is it possible to render template with AngularJs not on Page, but probably in memory? I need to prepare html to be send as email.
I guess i could render something in hidden div, then in some way assign it content to variable , but for me it looks ugly :(
You can take a look at $compile function: http://docs.angularjs.org/api/ng.$compile
Example:
function MyCtrl($scope, $compile){
// You would probably fetch this email template by some service
var template = '</div>Hi {{name}}!</div></div>Here\'s your newsletter ...</div>'; // Email template
$scope.name = 'Alber';
// this produces string '</div>Hi Alber!</div></div>Here\'s your newsletter ...</div>'
var compiledTemplate = $compile(template)($scope);
};
Sure, you can use the $compile service to render a template. The rendered template will be a DOM node that isn't attached to the DOM tree. And you don't have to attach it to get its content. You could do something like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile){
var compiled;
$scope.compileTemplate = function() {
var template = '<ul><li ng-repeat="i in [1, 2, 3]">{{i}}</li></ul>';
var linker = $compile(template);
compiled = linker($scope);
}
$scope.sendEmail = function() {
alert("Send: " + compiled[0].outerHTML);
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="compileTemplate()">Compile template</button>
<button ng-click="sendEmail()">Send email</button>
</body>
</html>
The reason that I've divided them into two different functions here is because when you compile and link it to the scope, the template isn't filled with data until after the next digest. That is, if you access compiled[0].outerHTML at the end of the compileTemplate() function, it won't be filled (unless you use a timeout...).

Resources