I am using angular ui router to handle some routing on my frontend. This is what my routing code looks like.
// angular config
$stateProvider.state('app', {
templateUrl: '/static/partials/home.html',
controller: 'NavCtrl'
});
$stateProvider.state('app.reader', {
url : '/reader/*path?start&end&column&page',
templateUrl: '/static/partials/reader.html',
resolve : {
panelContent : [
'$state', '$stateParams', '$http',
function ($state, $stateParams, $http) {
alert('resolving panel Content');
return []; // simplest thing possible to illustrate my point
}
]
},
controller: 'ReaderCtrl'
});
/// etc etc
$urlRouterProvider.otherwise('/reader/');
My html makes use of multiple nested views, I'll try and illustrate as best I can
index.html
<html>
<div ui-view></div> <!-- /static/partials/home.html gets injected here -->
</html>
/static/home.html
<html>
<!-- some side bar stuff -->
<!-- reader -->
<div ui-view></div> <!-- /static/partials/reader.html gets injected here -->
</html>
So I've got multiple levels of nesting going on
-- index.html
-- home.html
-- reader.html
Now, when I load the page for the first time, my alert message
alert('resolving panel Content');
fires just once.. that makes sense. However, let's say I click "next page" inside my pagination..
<!-- inside /static/partials/reader.html -->
<uib
pagination total-items= "totalItems"
ng-model= "pageNumber"
ng-change= "pageUpdate"
max-size= "maxPageNumbersDisplayed"
></uib>
this eventually fires a function inside my "ReaderCtrl"
$scope.pageUpdate(page) {
$state.go( '.', {page: page});
}
This updates the url, from going to something like this
/#/reader/<my path>
to something like this
/#/reader/<my_path>?page=2
Now for the part that has me tearing my hair out.
I get back to the "resolve" code block in the reader section of my routing.
The alert message happens twice.
By doing a bit of debugging in the web console, I discovered that the order goes
1) alert message in resolve
2) travel through the entirety of ReaderCtrl
3) lots and lots of angular calls
4) alert message (2nd time)
5) travel through entirety of ReaderCtrl a second time.
You might be inclined to know what is going on in NavCtrl, but I am not making any calls there. All that is in NavCtrl are functions that ReaderCtrl can inherit, in order to update the scope for /static/partials/home.html
So really, it appears as though I am stuck on step 3 here.
Does anyone have any ideas as to why my resolve block appears to be firing twice?
edit:
after a bit more debugging, I have seemed to figure out that the order goes something like this, starting right after the "updatePage" function executes.
1) first "resolving message"
-- the url has not yet changed
2) second "resolving message"
-- the url appears to have changed very shortly before this message
So, I guess my question now is...
why does
$state.go('.', args);
NOT change the url before the first alert fires, but DOES change the url at/near the second alert?
edit 2: could not end up fixing my issue, so I sort of hacked around it for the time being... I essentially made a function that did what I assume $state.go() was doing behind the scenes, and constructed the url.
function _mk_url(args) {
var url = "/reader";
var pageNumber = args.pageNumber || 1;
url += "?page=" + pageNumber;
var columns = args.columns || [];
columns.forEach(function(d) {
url += "&column=" + d;
});
//etc..
return url;
}
var args = {"columns" : ["a", "b", "c"], "pageNumber" : 2};
var url = _mk_url(args);
$location.url(url);
I was having this problem and found out it was because I was calling my resolve function manually somewhere else in the code. Search your code for panelContent() and you may find where it's getting triggered again.
I'd got this problem. The reason was in my html template. I used ui-sref directive in both child and parent elements
<li ui-sref="{{r.name}}" ng-class="vm.isCurrent(r)" ng-repeat="r in vm.settingsRoutes">
<span ui-sref="{{r.name}}" ng-bind-html="r.title"></span>
</li>
so when I clicked on span, I fired stateChange twice.
I've had the same bug.
And I found that I was changed $stateParams in one of the resolve functions.
The solution is make a copy from this object and then do what you want with a copy.
resolve: {
/** #ngInject */
searchParams: function ($stateParams) {
let params = angular.copy($stateParams); // good
// good:
if (params.pending === undefined) {
params.pending = true;
}
// bad:
if ($stateParams.redirect === 'true') {
$stateParams.pending = false; // this line changing the URL
}
return params;
},
}
Related
Hi I don't know angularJS yet I have a task in that. There is dashboard which is designed in angularJS. Now, in that there is link which will
open a pop-up. I have given a task to change that link to another pop-up but that pop-up is in jQuery. So, for me it is quite difficult to understand how to
change this.
I have a xml file where all the label in html are defined. This is the label from where the link is coming.
<subcolumn type="a" ngclick="decisioncomp();" styleName="proccheader labe1padding" text="Complete : " uniqueID="data31" />
Now, in the controller file of the same there is a function defined.
// complete link click
$scope.decisioncomp = function () {
if ($scope.data31 != "") {
ModalService.showModal({
templateUrl: "ChartpagePopup/Complete.html",
controller: "Complete"
}).then(function (modal) {
modal.close.then(function (result) {
$scope.customResult = "All good!";
});
});
}
else
alert($scope.waitingalert);
};
So, I came to know from here the link is going to html and controller. Now, I thought that if changed this ModalService.showModal to not to take controller
or if I send controller empty and replace my html with this html, my work should be done. So what I did is I changed in the Script file for that where this
funtion is defined.
I commented out line where it says that controller can't be empty.
self.showModal = function(options) {
// Create a deferred we'll resolve when the modal is ready.
var deferred = $q.defer();
// Validate the input parameters.
var controllerName = options.controller;
if (!controllerName) {
//deferred.reject("No controller has been specified.");
//return deferred.promise;
}
But then the link itself is not opening. I don't know where else to change. I am stuck here. Please someone help me.
I have angular code that fetches 8 json files asynchronously each via $http.get. This is called using ng-init="someFunct()" in a template code that is attached. Everything works great including filtering when a user types into an input text box. Filtering is especially important to my application.
To make filtering even better, I extract keywords from the said json files which I then wrap with <span class="tag" ng-click="filterWith='kywd'">{{kywd}}</span> in the hope that a user can click on the tags instead of type. This ONLY works if I embed the tags statically - in the real application I cannot know the keywords in advance. If I insert dynamically via $("#someContainerID").append(TAG_HTML_CODE) or similar it NEVER works!
In a nutshell this is what I need to achieve:
1) Dynamically inject multiple (in hundreds) such tags into DOM;
2) Inject the tags ONLY after everything else has loaded and compiled - but especially after the json files have been read and keywords extracted;
3) The tags that I inject need to respond to something like ng-click="filterWith='some_keyword'"
If there was a way to tell when AngularJS has finished all other processing - how great this would be! I have read everywhere and it seems so cryptic and confusing - pls HELP!
I have even tried the following code to no avail:
$timeout(function () {
$scope.$apply(function () {
//code that works on the keywords - works perfect!
var filterRegex = /\s*([\w\d.%]+)\s*/i;
var dom_elem = angular.element(document.querySelector("#filter_tags"));
dom_elem.html("");
for (var m = 0; m < tags.length; m += 1) {
var match = filterRegex.exec(tags[m][0]);
if (match != null) {
dom_elem.append($compile("<span data-ng-model=\"filterWith\" data-ng-click=\"filterWith='" + match[1] + "'\" title=\"" + tags[m][1] + "\" class=\"sk3tag clk\">" + match[1] + "</span>")($scope));
}
}
});
}, 10000, false);
}
EDIT: Narrowed the scope of my challenge to mainly one!
The bigger challenge for me is how to enable ng-click in the dynamically injected code and how to do it right.
Use Promise.all() to trigger when everything is loaded.
Earlier I had asked the question above. Somebody suggested I read further on directives instead. I did, fairly well. I came up with the following solution, to use click events on html code injected dynamically to DOM. I thank truly God for helping me figure it out, eventually. I no longer need to wait for the asynch data, whenever it comes and hence updates the model, my html tags are updated automatically - MVC magic! It seems to work great!
ANGULAR
//excerpt
myNgApp.controller('ctlTodayLatest', ['$scope', '$timeout', '$compile', '$http', function () {
$http.get('/filtertags.json').then(function (response) {
$scope.filterTags = response;
},
function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(response);
}
);
}]);
myNgApp.directive("myFilterTag", function () {
return {
template: "<span data-ng-repeat=\"tag in filterTags\" title=\"{{tag[0]}}\" class=\"mytag clk\" ng-click=\"filterWith(tag[0])\">{{tag[0]}}</span>",
link: function (scope, element, attrs) {
scope.filterWith = function (term) {
scope.fQ = term;
};
}
};
});
HTML
//excerpt
<div id="filter_tags" class="xip2 TAj" my-filter-tag></div>
So, my instructor thought it would be a great idea to throw in local storage and all that great nonsense the second week into learning Angular JS and basically told us to copy her code but change the names (as if that's learning). But anyways I have no idea how to work with angular js except for a few concepts and I need help finding the issues in my code. Any input would help. So far it looks as if the information from the form isn't being inputed to the html where it will be displayed. Here is my js fiddle. Any input is greatly appreciated
http://jsfiddle.net/g3tg5L15/1/
var app = angular.module('myApp', []);
app.controller("EmployeeController", function($scope, DataService){
$scope.empInfo = DataService.getEmpInfo();
$scope.newempInfo = {};
$scope.addNewEmpInfo = function(){
DataService.saveEmpInfo($scope.newempInfo.employee, $scope.newempInfo.street,
$scope.newempInfo.city,$scope.newempInfo.state, $scope.newempInfo.zip);
$scope.newempInfo = {};
};
$scope.removeEmpInformation = function(index){
DataService.removeEmpInfo(index);
};
$scope.clearInfo = function(){
DataService.destroyLocalStorage();
};
});
angular.module('myApp').service("DataService", function(){
var empInfoArray = [];
this.getEmpInfo = function(){
var employeeInfoArray = JSON.parse(localStorage.getItem("employeeInformationLS")) || [];
var empInfoArray = employeeInfoArray;
return empInfoArray;
};
this.saveEmpInfo = function(aName, aStreet, aState, aCity, aZip){
var savedEmpInfo = {employee : aName, street : aStreet, state : aState, city : aCity, zip : aZip};
empInfoArray.push(savedEmpInfo);
localStorage.setItem("employeeInformationLS", JSON.stringify(empInfoArray));
};
this.removeEmpInfo = function(aIndex){
empInfoArray.splice(aIndex, 1);
localStorage.setItem("employeeInformationLS", JSON.stringify(empInfoArray));
};
this.destroyLocalStorage = function(){
empInfoArray.splice(0);
localStorage.clear();
};
});
The main reason for the lack of response and debugging ability is due to AngularJS not loading correctly. For it to load you must change the dropdown in the left menu bar of jsFiddle from onLoad to No wrap - in <body> to load Angular correctly (as shown in the following screenshot).
The following surmises the issues I observed when debugging the code.
The getEmpInfo function within the DataService returns a new array each time it is called which prevents Angular from effectively monitoring it for changes. Instead of this function checking localStorage each time it is called it should just return the local array. The array can be simply loaded from localStorage when the service is first initialized.
The following update to the fiddle demonstrates this http://jsfiddle.net/g3tg5L15/6/. The changes implemented are as follows:
Change the dropdown in the menu bar of jsFiddle from onLoad to No
wrap - in <body> to load Angular correctly.
Added ng-click to 'Add Entry' button in HTML
<!-- Added ng-click to call addNewEmpInfo function on scope -->
<button ng-click='addNewEmpInfo()'>Add Entry</button>
Amended text on employeeInfo header to employee name rather than being hard coded value and added ng-click to remove in HTML.
<!-- Amended to add.employee rather than hardcoded value -->
<h3>{{add.employee}}</h3>
<!-- Added ng-click to call removeEmpInformation function on scope -->
<button ng-click='removeEmpInformation($index)'>X</button>
Amended the DataService to load from localStorage when it is initialized rather than initializing as an empty array.
var empInfoArray = JSON.parse(localStorage.getItem("employeeInformationLS")) || [];
Amend the getEmpInfo object to just return the local Array
this.getEmpInfo = function(){
return empInfoArray;
};
If necessary you can also watch for events triggered when localStorage changes, as included in the above fiddle. This will pick up changes from different tabs / windows if multiple are open. To monitor for these you must:
Include the services $window and $timeout in the DataService
angular.module('myApp').service("DataService", function($window, $timeout){
Add a trigger when a storage change occurs.
//Watch for storage events indicating changes to storage
angular.element($window).on('storage', function(event) {
//Check if the storage change was for our key
if (event.key === 'employeeInformationLS') {
//In a timeout (i.e. on next digest) update the array
//This could be done in a smarter way rather than clearing
//and rebuilding the entire array
$timeout(function(){
empInfoArray.splice(0);
var newArr = JSON.parse(localStorage.getItem("employeeInformationLS")) || [];
for (var i=0; i<newArr.length; i++){
empInfoArray.push(newArr[i]);
}
});
}
});
I have a email verification link, which looks something like
.when('/user/register/verify/:verify_code?', {
controller: 'AngularRegisterVerifyPage',
templateUrl: '/user/register/verify'
})
And my input field is like this.
input(ng-model="formData.verify_code", name="verify_code", type='text', class='form-control', placeholder='Verification Code', id="verify_code")
And this code should run when the template loads to insert the Parameter into the text field
document.getElementById('verify_code').value = "Test"; // Debugging Test Code
$scope.formSubmitted = false;
if ($routeParams.hasOwnProperty("verify_code")) {
document.getElementById('verify_code').value = $routeParams.verify_code;
}
But it would appear that the controller executes this before the template actually loads because when the page loads the input field is empty. Any information on how to do this properly would be great, I tried googling things like "Load Template after Controller loads" but haven't found anything. Thanks.
Edit:
I tried adding ng-init="loadCode()" to the input field, but it still doesn't work.
$scope.loadCode = function() {
if ($routeParams.hasOwnProperty("verify_code")) {
console.log('Called');
document.getElementById('verify_code').value = $routeParams.verify_code;
console.log($routeParams.verify_code);
console.log(document.getElementById('verify_code').value);
}
}
You don't need to change input value by manupulate dom in angularjs. Angular already has a lot of tremendous mechanism to help you reduce your development work.
In your case, you just change your code into this:
.controller('AngularRegisterVerifyPage', function($scope, $routeParams){
$scope.formData = {};
if ($routeParams.hasOwnProperty("verify_code")) {
//You change your value in your model, angular will render this to your html(view)
$scope.formData.verify_code = $routeParams.verify_code;
}
});
Here is a useful answer for angular newer: “Thinking in AngularJS” if I have a jQuery background?
Here is ngModel Document.
Enjoy it : )
I was brought in to fix a website that was on fire a couple months back. I've got most things under control and I'm down to fixing various wish-list items. One of them involved some angular code that I just can't seem to get to do what I want. On some pages there are videos followed by a short quiz. I need to update the user's scores after each event. So far, this proved to be easy enough for the total score which looked like this:
<a id="updateafterscore" href="~/user/leaderboard/" class="fill-div">
{{ profile.currentScore }}
</a>
And that got updated with this:
document.getElementById('updateafterscore').innerHTML = data.Data.CurrentScore;
So far, so good. However other elements on the page have, thus far, proved impossible to update. Here's what's on the page:
I added the "id="refreshvideo" myself so I could try to alter the tag. Finally, here's the angular module for simple-circle (I've left out the actual drawing code since it's not really relevant):
angular.module('thrive.shared').directive('simpleCircle', function() {
return{
replace: true,
template: '<canvas width="60" height="60" style="margin: -10px 0 0 -15px;"></canvas>',
restrict: 'E',
scope: {
value: '#',
color: '#',
bgColor: '#',
forecolor: '#',
radius: '#'
},
link: function (scope, elem, attrs) {
var multiplyLength = 1;
var canvasElem = elem[0];
var inMotion = false;
if (scope.value <= 2) {
multiplyLength = 5;
}
scope.$watch('value', function() {
drawCircle(canvasElem, scope.color, scope.value * multiplyLength, scope.value, scope.name);
});
function drawCircle(canvas, color, calculatedPoints, displayPoints, name) {
So, to the question: how the heck do I update the number that's displayed? I tried various things:
document.getElementById('refreshvideo').setAttribute('value', data.Data.VideoWatchedCount);
document.getElementById('refreshvideo').setAttribute('data-value', data.Data.VideoWatchedCount);
$scope.profile.videosWatched = data.Data.VideoWatchedCount;
None of these things worked. I inspected the canvas element in the source in the browser and I could see the value and data-value tags change to whatever I set them, but the image remained unchanged. Am I setting the wrong thing? (Perhaps whatever $watch is watching) Do I have to force some kind of re-paint of a canvas element?
#charlietfl means your solution is not actually using AngularJS - you're completely bypassing it. Angular provides two-way data binding between Javascript data and the HTML DOM. All you do is tell it where to draw data, and it will do that for you automatically, keeping it up to date from then on as the data changes.
In Angular, you never call getElementById and certain never set innerHTML because then you block Angular from doing its thing - in many cases you actually break it. Every one of those instances introduces a new bug while "patching" another.
Go back to your example template line:
<a ..attributes...>{{ profile.currentScore }}</a>
When it sees this, Angular will create what it calls a "watcher" on profile.currentScore. If its value right now is '1', it will render this as <a ...>1</a>.
Every digest cycle, that watcher will tell it to look at profile.currentScore to see if it changed. This line of code is pretty typical in JS:
profile.currentScore = 42;
Angular will "see" this happen through that watcher, and will automatically update the rendered template. You do nothing else - and if you ever feel that you need to, it almost always means something else is wrong.
If you're running into this a lot, try the "standard quick-fix". We see this a lot with people who didn't architect an application properly, and they're doing data model updates outside Angular's digest cycle where it can't "see" them. Try wrapping your update code in an $apply() call:
$scope.$apply(function() {
profile.currentScore = 42;
});
If you have a LOT of updates to make and you don't want to nest the call, you can also cheat, like this:
// Lots of stuff...
profile.currentScore = 42;
// Lots more stuff...
$scope.$apply();
You will know right away if you need to do this. If it works, you need to do it. :) If you get an error message in your console saying you're already in a digest cycle, you do NOT need to do it (it's something else).
I mentioned that I thought perhaps I was modifying the wrong profile variable and so it wasn't refreshing. So I looked back a little bit in the code that is supplying the numbers:
angular.module('episodes').controller('episodeCtrl', ['$scope', '$rootScope', '$window', 'episode', 'relatedCourses', 'Video', 'episodeItems', 'profile', 'Profile',
function ($scope, $rootScope, $window, episode, relatedCourses, Video, episodeItems, profile, Profile) {
// stuff skipped....
onComplete: function () {
Video.complete({ videoId: item.item.id }).$promise.then(function () {
item.progress = "Completed";
$scope.loadNextItem();
$scope.profile = Profile.get(); // <<-- gotten from somewhere
$.ajaxSetup({ cache: false });
$.get('/user/getCurrentUserPointsModel', function (data) {
if (data == "")
return;
$scope.profile.currentScore = data.Data.CurrentScore;
$scope.profile.videosWatched = data.Data.VideoWatchedCount;
$scope.profile.testTakenAndCorrectAnswerCount = data.Data.TestTakenAndCorrectAnswerCount;
Profile.save(); // <-- added
The value in $scope.profile is pulled from Profile, but I don't fully get how that gets where it is. I suppose I will need to figure that out because there's another place where these updates have to happen that lack that Profile information. Anyways I added the last 4 lines in place of this:
document.getElementById('updateafterscore').innerHTML = data.Data.CurrentScore;
... and all worked according to plan. I guess I tackle the other part later when I figure out how the data gets to the controller.
You can't do this that way. It's not Angular way of dealing with data.
Read the documentation before https://docs.angularjs.org/tutorial/step_04
If you need to modify your DOM using document.. probably sth wrong is with your code.
BTW. Stop using globals like:
document.getElementById('updateafterscore')