Accesing javascript variable in angularjs - angularjs

I am trying to accessing javascript variable and then change it in controller and then use it in route.. but it is showing the same old one.
var userEditid = 0;
app.controller("cn_newuser", function ($scope,$window) {
editUser = function (this_) {
$window.userEditid = this_.firstElementChild.value;
alert(userEditid);
//window.location.path("#/edit_user");
//$window.location.href = "#/edit_user";
}
route
.when("/edit_user", {
templateUrl: "/master/edituser/" + userEditid //userEditid should be 3 or some thing else but is showing 0
})
in abobe route userEditid should be 3 or some thing else but is showing 0

This is because the .when() is evaluated on app instantiation, when this global var (which is really not a great idea anyways) is set to 0, rather than when your controller is run. If you are trying to say, "load the template, but the template name should vary based on a particular variable," then the way you are doing it isn't going to work.
I would do 2 things here:
Save your variable in a service, so you don't play with global vars
Have a master template, which uses an ng-include, which has the template determined by that var
Variable in a service:
app.controller("cn_newuser", function ($scope,UserIdService) {
$scope.editUser = function (this_) {
UserIdService.userEditid = this_.firstElementChild.value;
$location.path('/edit_user');
}
});
also note that I changed it to use $location.path()
Master template:
.when("/edit_user", {
templateUrl: "/master/edituser.html", controller: 'EditUser'
});
EditUser controller:
app.controller("EditUser", function ($scope,UserIdService) {
$scope.userTemplate = '/master/edituser/'+UserIdService.userEditId;
});
And then edituser.html would be:
<div ng-include="userTemplate"></div>
Of course, I would ask why you would want a separate template per user, rather than a single template that is dynamically modified by Angular, but that is not what you asked.
EDITED:
Service would be something like
app.factory('UserIdService',function() {
return {
userEditId: null
}
});
As simple as that.

Related

Angular-SummerNote not working to set value with the controller context

I am using component based architecture but angular-summernote is not working with controller context.
Ex: <summernote>$ctrl.setvalue<summernote>
Edit
It is displaying the text rather than interpreting it.
<p>{{$ctrl.test1}}</p>
<summernote>{{$ctrl.setvalue}}</summernote>
**O/P**
<p>Hello</p>
<summernote>{{$ctrl.setvalue}}</summernote>
EDIT 2
Here is my Module
angular.module('SecondPage', ['summernote'])
Here is my Component
angular.module('SecondPage').
component('SecondPage', {
templateUrl: 'pqr/abc.html',
controller: function ArticlePageController()
{
var self = this;
self.test2 = 'Hello';
self.checkme="Check Me";
}
});

AngularJS - Initialize form data based on value

I am trying to add edit functionality to my app. In one view, I have a button that brings you to the edit page.
<button ng-click="editMission(selectedMission.key)">Edit Mission</button>
The value selectedMission.key is used to determine what to initialize the edit page's form data with.
In the controller the function looks like this:
$scope.editMission = function(key){
$location.path('/edit');
}
On the edit page I have:
<div data-ng-init="editInit()">
And in my controller I have:
$scope.editInit = function(){
var query = myDataRef.orderByKey();
query.on("child_added", function(missionSnapshot){
if (missionSnapshot.key()==key){
...
}
});
}
How can I run the initialize function based on the key value from editMission. Should I use some getter/setter approach with a global key variable? I tried just placing the editInit code in editMission but the form data does not populate on view load.
Common practice is to use a service to share variables between views/controllers.
So in your case you would use the getter/setter approach as you suspected. I don't know what exactly you're trying to do, but the service in your case would look something like this:
app.factory('missionKeyService', function() {
var currentMission= {};
return {
setMissionKey: function(missionKey) {
currentMission.key = missionKey;
},
getMissionKey: function() {
return currentMission.key;
}
}
})
And in your controller1:
//include 'missionKeyService' in your controller function params
$scope.editMission = function(key) {
missionKeyService.setMissionKey(key);
$location.path('/edit');
}
And controller2:
//include 'missionKeyService' in your controller function params
$scope.editInit = function() {
var currentKey = missionKeyService.getMissionKey();
//do something with this key
...
}

Use Service in angular

I use in service in my angular app as follows:
app.service('sharedProperties', function () {
var property;
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
$scope.Somefunc= function(Mname)
{
$http.post("SomeServlet",{
"name": Mname,
}).then(function(response) {
sharedProperties.setProperty(response.data);
window.location = "/blabla/page2.html";
});
};
And in page2 (another conroller) i get the value:
app.controller('controller2', function($scope,$http,sharedProperties) {
$scope.UserProperties = sharedProperties.getProperty();
});
and its doesnt work, always i get undefined.
In order for it to work, you must set the angular routing function which will take care of moving to another page without refreshing your current page (also called SPA - Single Page Application).
Take a look here, at the example in the end of the page there are the different pages and files in the mini system.
I remind you that angular is meant to work with single page applications, so if you refresh the page and change it into another one - You sort of lose the point of using it.

angular ui-router go to URL

How to use $state.go() if I have just the URL ?
Or can I get a state based on URL? (and than use $state.go(state))
I'm asking because I had to intercept the $urlRouterProvider.otherwise() to wait for an other plugin loads some external modules.. and now I need to continue and call the URL that call otherwise()
In place of $state.go(), you can use $location service as well.
i.e.
$location.path(url)
Please take care of not using # in URL. You can also use window.location.href
I had a similar problem, and $location wasn't helping, so I wrote a function to get the state from the url.
NB: I am using nested states based on ui-router.stateHelper, so I traverse my nested states object, testing for url matches. It would be slightly different when using dot notation to define nested states - and even easier if you don't use nested states at all!
function goPath (path) {
var target;
var arr = path.match(/\/\w+/g);
var i = 0;
var testState = function (state, i) {
if (state.url === arr[i]) {
target = state;
if (state.children && state.children.length && arr.length > i+1) {
i++;
state.children.forEach( function (childState) {
testState(childState, i);
});
}
}
};
myStatesObj.forEach( function (state) {
testState(state, i);
});
$state.go(target.name);
};
I was on a similar situation, what I did is changed the location to a different path and reset it to the current after a timeout like this
var path = $location.path();
$location.path("/");
$timeout(function(){
$location.path(path).replace(); //use .replace() so the empty path won't go to the history
},0);
i'm adding a full answer to this due to the high number of views.
NOTE: location.search() is only used where you need to handle a URL with a query string in it. otherwise use location.path() only.
your ui.router login state should look something like ...
.state('login', {
url: '/login',
templateUrl: 'routes/login/login.html',
controller: 'LoginController',
controllerAs: 'loginCtrl',
authenticate: false,
params: {
fwdPath: undefined, // Location to forward to on login success
fwdQueryStringObject: undefined // Query string object to use on login success - retrieved from $location.search()
}
})
your 401 (unauthorised) interceptor should look something like ...
state.go('login', {fwdPath: location.path(), fwdQueryStringObject: location.search()});
your login controllers login function should call your login service's login function. the code INSIDE the controllers login function should look something like ...
loginService.login(self.username, self.password).then(function (response) {
// local vars prevent unit test failure
var fwdPath = state.params.fwdPath;
var fwdQueryStringObject = state.params.fwdQueryStringObject;
if (response.status === 200) {
timeout(function () {
if (fwdPath != null) {
location.path(fwdPath).search(fwdQueryStringObject);
location.replace();
} else {
state.go('home');
}
}, 400);
} else {
self.error = true;
}
self.pending = false;
}
};
and finally your unit tests ...
state.params.fwdPath = '/login/list';
state.params.fwdQueryStringObject = {q: 5};
spyOn(location, 'path').and.callThrough();
spyOn(location, 'search').and.callThrough();
...
expect(location.path).toHaveBeenCalledWith('/login/list');
expect(location.search).toHaveBeenCalledWith({q: 5});

Angular $scope losing child data in certain situation

I'm having an issue where, when I simply console.log($scope.visitors) my data is fine, but when I console.log($scope.visitors) and then try to open a AngularUI Bootstrap dialog, the $scope.visitors.optionalFields object is empty.
Now, I've spent some time trying to replicate the issue in jsbin and I wasn't able to get it to happen, so it may be difficult to answer; just hoping somebody might have an idea what could be causing it.
So I have an array of objects like this:
$scope.visitors = [
{
company:"one",
optionalFields: {
passportNumber:"ppt",
contactNumber:"tel",
licensePlate:"1234"
},
firstName:"some",
lastName:"guy",
}
]
I ng-repeat through these with visitor in visitors and each one has a button with ng-click="editVisitorDialog(visitor)"
Now, if I make editVisitorDialog like this:
$scope.editVisitorDialog = function (visitor) {
console.log($scope.visitors);
console.log(visitor);
}
Then both $scope.visitors and visitor look good, they have all of their properties.
However, if I simply add to this function (i.e., the log calls are still at the top of the function), each visitor in $scope.visitors will have an empty optionalFields object.
$scope.editVisitorDialog = function (visitor) {
console.log($scope.visitors); // missing the optionalFields items
console.log(visitor); // missing the optionalFields items
var modalInstance = $modal.open({
templateUrl: 'app/checkin/edit_visitor/edit_visitor.html',
controller: EditVisitorController,
resolve: {
visitor: function () {
return visitor;
}
}
});
modalInstance.result.then(function (result) {
console.log(result)
}, function () {
});
}
When you call console.log() with an object it doesn't really log the object. It's rather like an inspection tool where you can see the current state, not the state at the time console.log() was called.
Try console.log(visitor.optionalFields.passportNumber) instead and I guarantee that it will log "ppt" (in your example).
That in turn means that somehwere in the added code the optional fields get lost.

Resources