Cannot read property '$scope' of undefined - javascript

When I receive a html content in angular app, I inject it in the html document, but then can't get it. Example minimized code on plunker and in javascript
I have next controller:
class ReadCtrl
constructor: (#$scope, #$rootScope, #$compile, #$sce, #$window, #webService) ->
#getData()
getData: ->
promise = #webService.getBookText()
promise.then #success, #error
success: (response) =>
#$scope.html = response.data
#$scope.trustedHtml = #$sce.trustAsHtml(#$scope.html)
console.log $('.book_contents').first().children()
ReadCtrl.$inject = ["$scope", "$rootScope", "$compile", '$sce', "$window", "webService"]
angular.module("bookReader").controller "ReadCtrl", ReadCtrl
Method success save html to variable trustedHtml, and then it binds to view:
<div class="br_container">
<div class="br_source_container" ng-bind-html="trustedHtml">
</div>
</div>
Content shows, but this console.log $('.book_contents').first().children() has zero elements. And when i try to insert something like #$rootScope.$digest() the error throws:
Error: [$rootScope:inprog] $digest already in progress
That because of => in method, which compiles to:
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
this.success = __bind(this.success, this);
So if I change => to -> there is another error:
TypeError: Cannot read property '$scope' of undefined
In the first line of success function. So this is undefined in success function, perhaps because it is called with promise.
Another method with $('.br_source_container').html(#$compile(#$scope.trustedHtml)(scope)) occurs the same errors.
So, I need to get DOM html of the inserted part.

So, the problem solves with timeout respectful for charlietfl
This how it wors

Related

how do I fix exception on calling length on an empty array

I have this angular service which on startup contains an empty array. In the getter, I log what it is returning. I would like avoid having to write logic around a logging statement, and I would like the logging statement to stay, for now.
here's the provider:
appInstance.service('ActivityNavigationDataService',
['$log', '$rootScope', 'UIManager',
function($log, $rootScope, UIManager) {
$log.debug('ActivityNavigationDataService constructor');
$rootScope.activities = [];
UIManager.registerActivityListener($rootScope, activitiesUpdated);
function activitiesUpdated(event, activities) {
$rootScope.activities = activities;
}
this.getActivities = function() {
$log.debug('returning ' + $rootScope.activities.length + ' activities');
return $rootScope.activities;
};
}]);
here's the error:
TypeError: Cannot read property 'length' of undefined
at Object.getActivities (ActivityNavigationDataService.js:28)
at new ActivityNavigationServiceController (ActivityNavigationServiceController.js:31)
at Object.instantiate (angular.js:5055)
at $controller (angular.js:11015)
at UIManager.js:40
at processQueue (angular.js:17051)
at angular.js:17095
at Scope.$digest (angular.js:18233)
at angular.js:18462
at completeOutstandingRequest (angular.js:6362) "Possibly unhandled rejection: {}"
thoughts?
Thnx, Matt
edit:
I think the problem is the ActivityNavigationDataService is not finished loaded and constructed by the time activitiesUpdated is called.
I am loading the service via define[] like this:
define(['services/ActivityNavigationDataService',
// theres others here
'controllers/UIManager'],
function() {
'use strict';
var appInstance = angular.module('obdPortletApp');
appInstance.controller('obdMasterController', ['$rootScope','$scope', '$log', 'UIManager',
function($rootScope, $scope, $log, UIManager) {
UIManager.initialize();
UIManager.buildUI();
}]);
}
);
The UIManager.buildUI() method uses ocLazyLoad to load additional resources, which in turn push activities to the ActivityNavigationService through a broadcasted message, not direct reference to the service.
So I think something is off on timing.
Your activitiesUpdated() handler is getting undefined for activities. If you are the one returning the activities make sure you return an empty array. However, if you don't, you could do something like this:
function activitiesUpdated(event, activities) {
$rootScope.activities = activities || [];
}

JS $scope.something equals to a function

I can't understand what $scope.search is doing there, like, what it is doing when it set equals to the function? And, if i want to do in other way, how should i do?
(i am using angular js, 1.6 version)
$scope.search = function(){
query.get($scope.username , {
success: function(gameScore) {
console.log(gameScore);
return gameScore;
},
error: function(object, error) {
console.log("Sorry, this user does not exist yet");
}
});
};
You can call $scope.search() from anywhere in your controller. You can also do something like ng-click=search() on any element in a template that is using that controller.
Calling $scope.search() will either return gameScore or print an error message to the console.
Not sure if this function is written in a general controller or a component controller
Since you are using 1.6
Incase of it being a component controller you could attach this function to component controller and use it in your template or component
angular.module('app',[])
.component('testComponent', {
bindings: {}.
tempalate:'<div>$ctrl.getValue()</div>',
controller: function(){
var ctrl = this;
ctrl.getValue = function() {
console.log('log your value');
}
}
});

How to declare a variable accessible to whole function in angularjs?

(function (angular) {
'use strict';
angular
.module('app')
.controller('ListSharedContentCtrl', ['$scope','$log','UserService', 'ContractService','ContentOwnerService','PlatformPartnerService',function ($scope, $log, userService, contractService,contentOwnerService,platformPartnerService) {
$scope.init = function () {
var contractIds =[];
var contentOwnerId;
var platformPartnerId;
var user=userService.getCurrentUser('true');
var contentOwner=userService.isCurrentUserIsContentOwner();
var platformPartner=userService.isCurrentUserIsPlatformPartner();
if(contentOwner == "true")
{
contentOwnerService.getContentOwnerId().then(function(savedContentOwnerId) {
contentOwnerId=savedContentOwnerId;
console.log(contentOwnerId);//here I can log the value
},function(error) {
$log.error("Error fetching contract id:" + error.message);
});
}
console.log(contentOwnerId); //but Here I cant log the value..Its showing undefined
} $scope.init();
}]);
})(angular);
Now my question is how to make the scope of the variable "contentOwnerId" available to whole function?Please anyone help me I cant figure it out..Thanks in advance..!
You are declaring contentOwnerId twice; once inside the if block, once outside it. The one outside is declared, but never assigned a value. It should be null where it is showing null.
The reason why you are getting the contentOwnerId undefined is that it is undefined until when the getcontentOwnerId() promise succeed!
if you do
var contentOwnerId = "before resolving the promise";
at the beginning of your init() you will probably have that string logged to console, instead of undefined
use $scope.contentOwnerId instead of var contentOwnerId.
See $scope.contentOwnerId is available to whole controller i.e ListSharedContentCtrl.
normal javascript variable are limited to functions where as $scope is available to entire CONTROLLER
The .then() method belongs to a promise.
This means it won't be executed immediately, but later in the angular life cycle.
Your console.log() will always log 'undefined' because your variable won't be initialized there.
You can try this to log the value:
$scope.$watch(
function() { return contentOwnerId; },
function(newContentOwnerId, oldContentOwnerId) {
console.log(newContentOwnerId);
}
);

AngularJS service TypeError

I want to capture the url of my query in an AngularJS service as this
var mortgageloanService = angular.module('loanstreetIpadAppApp', []);
mortgageloanService.factory('updateTable', function($http) {
return {
getParams: function() {
var url = 'https://api.mongolab.com/api/1/databases/angularjs-intro/collections/users?apiKey=terrPcifZzn01_ImGsFOIZ96SwvSXgN9';
console.log('in service mode');
console.log(url);
return $http.get(url);
}
};
});
This is my controller.js code
angular.module('loanstreetIpadAppApp')
.controller('Mortgage_LoanCtrl', function ($location, $scope) {
$scope.update_result = function(updateTable) {
updateTable.getParams().success(function(loan){$scope.loan = loan});
console.log($scope.resulttable);
};
});
On my view page, i have a button which onclick shud call the update_result function. But whenever i click on the button i get the following error
TypeError: Cannot read property 'getParams' of undefined
at Scope.$scope.update_result (http://localhost:9003/scripts/controllers/mortgage_loan.js:22:16)
at http://localhost:9003/bower_components/angular/angular.js:10567:21
at http://localhost:9003/bower_components/angular/angular.js:18627:17
at Scope.$eval (http://localhost:9003/bower_components/angular/angular.js:12412:28)
at Scope.$apply (http://localhost:9003/bower_components/angular/angular.js:12510:23)
at HTMLButtonElement.<anonymous> (http://localhost:9003/bower_components/angular/angular.js:18626:21)
at HTMLButtonElement.jQuery.event.dispatch (http://localhost:9003/bower_components/jquery/dist/jquery.js:4430:9)
at HTMLButtonElement.elemData.handle (http://localhost:9003/bower_components/jquery/dist/jquery.js:4116:28)
Anyone knows how to solve this issue?
In order to use your updateTable's factory inside your controller, you need to inject it. So, your controller should look like this.
angular.module('loanstreetIpadAppApp')
.controller('Mortgage_LoanCtrl', function ($location, $scope, updateTable) {
$scope.update_result = function() {
updateTable.getParams().success(function(loan){$scope.loan = loan});
console.log($scope.resulttable);
};
});
Notice that I've removed "updateTable" as "$scope.update_result"'s parameter since it would overwrite your updateTable object inside that closure.

Using Typeahead and AngularJS with loaded data in scope results in "TypeError: Cannot call method 'then' of undefined"

When trying to use this concept for a typeahead, I created the following code (which works with the json data, just not with this new data).:
HTML
<input type="text" ng-model="result" typeahead="suggestion for suggestion in instObjs($viewValue)">
JS
function NavbarCtrl ($scope, cService, $http, limitToFilter) {
$scope.institutions = [];
cService.getInstitutions().then(function(institutions){
$scope.institutions = institutions;
});
$scope.instObjs = function(institutions) {
return $scope.institutions.name.then(function(response){
return limitToFilter(response.data, 15);
});
};
};
It seems, that you are trying to use $scope.institutions.name before it gets assigned. I suppose, that $scope.instObjs is called before your callback to cService.getInstitutions() is called.
But this is a consequence, not cause.
I can see you are trying to access property name of array. Are you sure you didn't mean something like this:
$scope.instObjs = function(institutions) {
return institutions.name.then(function(response){
return limitToFilter(response.data, 15);
});
};
I mean using your function's parameter instead of array. That would make a sence. And this can be a cause.

Categories

Resources