In short my problem is this: I want to use angular constant functionality to save values that I will need in my app. I was wandering if one could build a property using the value of another property of the same constant. Like this:
app.constant("url", {
basicUrl: "/svc",
managementPanel: basicUrl + "/managemnent.html"
// and so on...
});
Is there any way one can achieve this? I tried using the "this" keyword but it referenced the window object.
You can put it all to function:
(function() {
var constant = {};
constant.base = 'base';
constant.nested = constant.base + '/nested';
constant.nested2 = constant.nested + '/nested2';
app.constant('test', constant)
})();
You will need to use a factory instead of the constant shorthand for this.
app.factory("url", function() {
var url = {};
url.basicUrl = "/svc";
url.managementPanel = url.basicUrl + "/managemnent.html";
return url;
})
Related
So I'm basically trying to get a property from my $rootScope when the page loads. I need this property so I can display the value in my form.
After testing this:
console.log("DEBUG $rootScope", $rootScope);
console.log("DEBUG $rootScope.localClient", $rootScope.localClient);
I've noticed that $rootScope contains a localClient property, but $rootScope.localClient is undefined. Why is this?
See console screen below.
Here is where I fill the localClient object
function setClient(client, tvaNumber) {
if (tvaNumber) {
if (angular.isUndefined($rootScope.localClient))
$rootScope.localClient = {};
$rootScope.localClient[tvaNumber] = client;
}
}
Try accessing it like this,
console.log("DEBUG $rootScope.localClient", $rootScope['localClient']);
You must make sure the attribute loaded before use it, because JavaScripte always pass a reference to an object. Or you can try console.log(JSON.parse(JSON.stringify($rootScope)) get the real value.
One example:
var a = {}; console.log(a);a.test = '1';
I have an AngularJS Service defined as follows:
function testService(testProvider) {
var ref = this;
ref.firstLevel = {};
ref.secondLevel = {};
initialize();
function initialize() {
testProvider.getData().then(function(result) {
ref.firstLevel = result;
ref.secondLevel.testData = result;
});
}
}
The testProvider is a simple wrapper around $http.get that fetches data from a JSON. The controller copies over these properties:
function testController(testService) {
var vm = this;
vm.firstLevel = testService.firstLevel;
vm.secondLevel = testService.secondLevel;
}
When I create bindings in my template, the second level works, the first level doesn't.
<!-- Doesn't work -->
<p>{{vm.firstLevel.testProperty1}}</p>
<p>{{vm.firstLevel.testProperty2}}</p>
<!-- Does work -->
<p>{{vm.secondLevel.testData.testProperty1}}</p>
<p>{{vm.secondLevel.testData.testProperty2}}</p>
See this Plunker for a working example:
https://plnkr.co/edit/pLInqcaJNhhbQWbvTUEE
Why doesn't the first level example work?
This is because when you overwrite an object in Javascript, you actually lose the reference to the actual object.
testProvider.getData().then(function(result) {
ref.firstLevel = result;
ref.secondLevel.testData = result;
});
Here ref.firstLevel = result overwrites the reference to the object that was initialized to {}. Any data bindings that you had on that object would be lost after this line.
Whereas, by doing ref.secondLevel.testData = result, you are not rewriting the object, rather you are only modifying the object by adding an extra key testData. Thus the reference is still preserved and so are the AngularJS bindings.
See this answer for more clarity.
I am trying to develop a mobile application in which i am getting JSON object using javascript page main.js,now I am trying to print the object using angualjs Controllers,but could not find any way.CAn anyone help me out on this?
function written in Main.js`
function getViewColumnsSuccess(result){
var httpStatusCode = result.status;
if (200 == httpStatusCode) {
var invocationResult = result.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
var result = invocationResult.text; //var FinalCol=reult;
} else {
alert("Error. httpStatusCode=" + httpStatusCode); } } }
The var result I want to get in DemoController in another page
app.controller('tableCtrlNew', function($scope,$http) { });
First controllers are not for print data, for that you should dataBinding, in views.
For Example:
In your controller you have this var;
$scope.name="John Doe";
So, then to print that in some view, you shoud print that in some view that has that scope, so to print in one view(html) that is simple like:
<span class="labelName"> {{name}}</span>
It is data-binding, with this you automatically print data from a controller into a view, but remember, it must be in the same scope to works.
Regards.
Assign Result to Window object
window.result = invocationResult.text;
In controller you can use $window
app.controller('tableCtrlNew', function($scope,$http,$window) {
console.log($window.result);
});
I'm trying to use a custom Angular directive with a custom attribute, i.e. :filterBy=:filter. This is being done with a custom directive like this:
<foo filterBy=location filter=ABC></foo>
The service:
function Foo($resource) {
return $resource(base + 'Foo');
}
The ngResource call:
var filterBy = attrs.filterBy;
var getSegments = Foo.get({filterBy: attrs.filter, limit: attrs.limit, offset: attrs.offset});
returns this:
http://localhost:8000/base/Foo?filterBy=ABC&limit=30 (notice it says "filterBy" instead of location")
It should be returning this resource instead:
http://localhost:8000/base/Foo?locations=Bar&limit=30
It seems the filterBy is being turned into a string in the ngResource call. I wan't it to use the value of the attrs.filterBy, but it doesn't like dot notation in the parameter value.
I've also tried this:
var getFilter = function() {
return attrs.filterBy;
};
But when I do that, the resource URL turns into:
http://localhost:8000/base/Foo?getFilter=Bar&limit=30
Note the "getFilter" is the parameter now. So is there any way to create a custom parameter?
var filterBy = attrs.filterBy;
var params = {limit: attrs.limit, offset: attrs.offset};
params[filterBy] = attrs.filter;
var getSegments = Foo.get(params);
When you write filterBy: value then filterBy is an identifier. It's static. It has no relation whatsoever to any variable.
params[filterBy] = attrs.filter; on the other hand dynamically adds a property and the value within the brackets is an expression that can be resolved to a string. So it can be a variable.
Very begginer question, sorry about that!
I understand how to store constants in services with AngularJS, for example:
.value('baseUrl', 'http://127.0.0.1:8001/api/v1/')
But how can I create another constant that uses another one?
It seems there is no DI in values ?!?
For example, If I want to create a GetUsersUrl which is baseUrlstring + 'Users/' (concatenation)
I guess it's simple...but unable to find how to do it.
Thank you.
You can store values in services, configure it in the run phase, and then access the values later. For example:
.factory('UrlService', function() {
var UrlService = {};
UrlService.baseUrl = undefined; // you can set a default value
UrlService.getUsersUrl = function() {
if (UrlService.baseUrl === undefined) {
return undefined;
} else {
return UrlService.baseUrl + '/Users/';
}
};
return UrlService;
});
The run phase happens after config.
.run(function(UrlService) {
UrlService.baseUrl = 'localhost:8001/api/v1';
});
Then, in your controllers, etc. you can inject UrlService and do
UrlService.getUsersUrl()
Edit: Rewrote the answer.
Edit 2: Another approach.
It also appears to me that you only really need baseUrl to be a constant. So, you could do:
.value('baseUrl', 'localhost:1337')
.factory('urlService', ['baseUrl', function(baseUrl) {
return {
getUsersUrl: function() { return baseUrl + '/users/'; },
// OR
usersUrl: baseUrl + '/users/' // it can also be a primitive value
}
}]);
This approach works (and is more "the Angular way") if you do not need to actually configure the baseUrl. For example, if you can fill in the appropriate value of the baseUrl based on which environment (dev, production, etc) is running, you wouldn't need to configure it. Or, if the value is constant.