How to set dynamic variable name in Angularjs controller - angularjs

This is my controller code :
var selectableFields = ["customerName", "customerAddress"];
angular.forEach(selectableFields, function(field, key) {
var value = $.jStorage.get(field); //using jStore to get the values
$scope.field=value;
});
The objective is to be able to access {{customerName}} and {{customerAddress}} in the view.
Can anyone please tell me what is the correct way of doing this?

Use $scope[field] = value; instead.
With $scope.field, you're creating a new attribute named field.

var pages=["kedi","köpek","tavşan","ayi"]
pages.map(page =>{
$rootScope["adChangeUrl"+page]="dene.com"
$rootScope["imgSrc"+page]="images/deneme.png"
$rootScope["imgAdTitle"+page]="deneme.com"
$rootScope["imgAdAlt"+page]="https://deneme.com/"
}
)
//console.log Output
adChangeUrlayi: "dene.com"
adChangeUrlkedi: "dene.com"
adChangeUrlköpek: "dene.com"
adChangeUrltavşan: "dene.com"
imgAdAltayi: "https://deneme1.com/"
imgAdAltkedi: "https://deneme1.com/"
imgAdAltköpek: "https://deneme1.com/"
imgAdAlttavşan: "https://deneme1.com/"
imgAdTitleayi: "deneme.com"
imgAdTitlekedi: "deneme.com"
imgAdTitleköpek: "deneme.com"
imgAdTitletavşan: "deneme.com"
imgSrcayi: "images/deneme.png"
imgSrckedi: "images/deneme.png"
imgSrcköpek: "images/deneme.png"
imgSrctavşan: "images/deneme.png"

Related

Value from $rootScope is not loaded properly

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';

Use constant property to build another property inside the same constant angularjs

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

Notable to link javascript object and angularjs in controllers

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

Passing JSON object as parameter from View to Controller function?

Basically I've a panel called DummyPanel, Now on dummypanel initialize event I've called a controller function like as follows:
var me = component;
var fieldCollection =
{
"Order" : 'ordNumber',
"Ref": 'refNumber'
};
me.fireEvent('myControllerFunction','Param1', fieldCollection, 'Param3');
Now I want to get fieldCollection JSON object value within function myControllerFunction, to get value from fieldCollection I'm using following code:
myControllerFunction(param1, collection, param3)
{
Ext.Msg.alert(collection.Order);
}
But it does not return anything. So please let me know how to resolve this problem!!
Any comment will appreciated!!
I'm not quite sure what it means "But it does not return anything", but I'll try.
So, your "DummyPanel" view have a alias or itemId property. In yor controller (in init() function), you need "keep track" of your view. For example:
In your view:
me.fireEvent('myEventName','Param1', fieldCollection, 'Param3');
In your controller:
init:function(){
var me = this;
this.control({
'panel[itemId=your-view-itemId]': { // call your function after event
myEventName: me.myControllerFunction
}
});
...
},
...
myControllerFunction: function(...) {
...
}
Should it not be
Ext.Msg.alert(collection["Order"])?
Or if you want to keep Ext.Msg.alert the way it is fieldCollection should be defined this way
var fieldCollection =
{
Order : 'ordNumber',
Ref : 'refNumber'
};

Adding a computed field to every element of an array in an AngularJS model

I'm pulling an array of users into my AngularJS model from a JSON datasource. This data is being rendered in a table, and I'd like to create a column that is computed from two values of the existing user object, without modifying my underlying data service.
// My model
function UserListCtrl($scope,$http) {
$http.get('users').success(function(data) {
$scope.users = data;
});
};
In my partial template, I know I can do something like this:
<tr ng-repeat="for user in users">
<td>{{user.data / user.count | number:2}}</td>
</td>
But I'd rather add that field into the model, so I can use it like so:
<td>{{user.amplification}}</td>
How do I add the "amplification" field to every user in my model?
As an aside, is it possible to use the orderBy filter on something like this:
<td>{{user.data / user.count | number:2}}</td>
You can eather:
Just after loading user do:
$http.get('users').success(function(data) {
$scope.users = data;
$scope.user.amplification() = function() { return $scope.user.data / $scope.user.count; }
});
And use as {{user.amplification()}}
Anywhere at controller:
$scope.$watch('user', function() {
$scope.userAmplification = $scope.user.data / $scope.user.count;
}, true);
$http.get
Or if user.data/count do not change, do same as 1. but staticly calculate:
$http.get('users').success(function(data) {
$scope.users = data;
$scope.user.amplification = $scope.user.data / $scope.user.count;
});
And OrderBy could be used on any expression (uncluding result of other filter)
If you don't need your amplicification() function to update when the data and count properties on your user update, you can do something like this in your controller:
$scope.users.forEach(function(user) {
user.amplification = function() {
return user.data / user.count;
};
});
Adding a second answer as I feel it's appropriate as it's distinct from my first one.
After a little looking around, I found the method I originally posted falls over if you try to add new rows dynamically, or new elements to the array which depend on the computed value. This is because the $scope.array.forEach() will only run when the controller is created.
The best way to solve this problem is to create a properly defined object which contains the options you want. e.g.
function Task(id, name, prop1, prop2) {
this.id = id;
this.name = name;
this.prop1 = prop1;
this.prop2 = prop2;
this.computedProperty = function () {
return this.prop1 + this.prop2;
};
}
This is far more flexible as each new object created will have the new property.
The only downside is that in your ajax success callback, you'll need to pass each of your users into your 'Users()' constructor.
What worked for me was to add a loop and add the property to each item in that loop. I used a property of the controller but I am sure you can use scope the way you are approaching it in the question.
function(result) {
self.list = result;
angular.forEach(self.list, function(item) {
item.hasDate = function() {
return this.TestDate != null;
}.bind(item); // set this context
});
}
Then in my markup I just used it like this.
<div ng-repeat...>
<div ng-show="item.hasDate()">This item has a date.</div>
</div>

Resources