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
Related
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>
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.
I am learning Angular using W3Schools.
I just modified an example about "Services"... The following is the code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{hex}}</h1>
</div>
<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
When I update the textbox, the "HEX" part is not updating. Why?
Your hexafy.myFunc is called only once when the controller is initialized, hence only the initial value is converted to hex. If you want a function to be called on the value change of a scope variable in runtime, you need filters. AngularJS has a lot of inbuilt filters that are ready to use.
You can also define a custom filter, just like you define services or controllers.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{num | hexafy}}</h1>
</div>
<p>A custom filter that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.filter('hexafy', function() {
return function (x) {
return Number(x).toString(16); // Also convert the string to number before calling toString.
}
});
app.controller('myCtrl', function($scope) {
$scope.num = 200;
//$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
Further reading: AngularJS Filters
NOTE: A filter is a good idea if you're gonna be using the hexafy functionality at multiple places in/across views. Otherwise, it is just an overkill and the $scope.$watch method will work fine for you, as described in other answers
$scope.hex is not updating because there're no way for it update itself.
The hexafy.myFunc is called only once when the controller is loaded for the first time.
If you want want the $scope.hex property to change with num, you might need a watch on the num property.
$scope.$watch('num', function(newVal, oldVal) {
$scope.hex = hexafy.myFunc($scope.num); /// or newVal
}
The function passed in $scope.$watch will be called everytime the value of $scope.num changes.
for more info see https://docs.angularjs.org/api/ng/type/$rootScope.Scope (the watch section)
Hope it helps.
No need of a service here, you can simple use $watch on the num. See below code snippet, it will update your ui, I have updated your controller code, please check.
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = "some default val";
$scope.$watch('num', function(newValue, oldValue) {
$scope.hex = newValue.toString();
});
});
Your Text box is only bind to 'num'. '$scope.hex is not binded to your text box'. So that it is not update when you typing text. You could use '$watch' on 'num'. Read here
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.$watch('num', function() {
$scope.hex = hexafy.myFunc(parseInt($scope.num));
});
});
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;
}
I try AngularJS for the first time and I'm stuck on a problem.
In the debugger I see that the scope variable '$scope.xml' is correctly updated, but the display needs a second pass (second click) to refresh.
Here is a Plunker to see my problem : http://plnkr.co/edit/9PJsGeDqwjC6nmZHcEJV
I'm looking in the documentation but I can not find track to understand what I did not do well
Thank's a lot for your help !
<!doctype html>
<html ng-app="testAngularJS">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="testXML">
<div>XML<br/><textarea cols="60" rows="15" ng-model="xml" name="xml">{{xml}}</textarea></div>
<div><button ng-click="listTypDoc()">List !</button><br/>
<br/><button ng-click="clearXML()">Clear</button></div>
</div>
<script type="text/javascript">
var app = angular.module('testAngularJS', []);
app.controller('testXML', function($scope){
$scope.url = 'listeTypDoc.txt';
$scope.listTypDoc = function() {
$.ajax({
type:"GET",
url: $scope.url,
xhrFields: {
withCredentials: false
},
crossDomain: false
}).done(function ( data ) {
$scope.xml = data;
debugger;
});
};
$scope.clearXML = function() {
$scope.xml = '';
};
})
</script>
</body>
</html>
Because you are using a request outside the angularjs, you need to call $apply() after setting the data to the $scope.xml. Take a look in the apply method:
http://docs.angularjs.org/api/ng.$rootScope.Scope
But it's better to use the services angularjs provides instead of using jquery.