how to access parents scope from ng-click - angularjs

I need to pass the value of $scope.correct into the checkAnswer function but it keeps coming up undefined. ng-click only seems to understand it's own scope. What am I doing wrong?
angular.module('Tutorials', ['functions']).controller('getAnswers', function ($scope, $element){
$scope.verbs = conjugate(conjugationsets[tutorial_number][questionnum]);
$scope.correct = $scope.verbs.conjugations[0].text;
$scope.randomizeAnswers = function () {
fisherYates($scope.verbs.conjugations);
}();
$scope.checkAnswer = function (answer, correct){
checkanswer($scope, answer, correct);
}
});

You can use $scope.$parent to access the parent scope.
$scope.checkAnswer = function (answer){
checkanswer($scope, answer, $scope.$parent.correct);
}
Note: I haven't gone through the complete problem to see whether there is an better way to solve the problem

Related

angularjs share variable between functions

Within a controller, I'd like to share data between two functions. For example:
controllers.controller('rightDrawerCtrl', function ($scope, $http) {
$scope.shared_id;
$scope.getId = function () {
// get the id via $http, using a secondary id to retrieve the shared_id
}
$scope.useId = function () {
// use the shared_id to make a different api call
}
});
In this example however, when useId() is called, shared_id is undefined.
I presume this is because useId was 'created' while shared_id was undefined, so hasn't been notified of the new value.
The only way I've found to fix this is by using two controllers: Share data between AngularJS controllers
Is there a better way to do this, using only 1 controller?
$scope.shared_id;
After the above statement the shared_id variable of $scope should be undefined - because you haven't assigned it any value.
Despite this the variable is still accessible inside any scope functions because $scope is global for them. And don't forget that you should access it like $scope.shared_id in all the places.
However if you initialize it in the following manner:
$scope.shared_id = 'no id';
.. it would not return undefined.
You can initialize this variable via ng-init too.
Call userId() function when getId() function get result from $http request.
Looks like I simply had to wrap the variable assignment in $scope.$apply
$scope.$apply(function() {
$scope.shared_id = 1234;
});
You can use like this with this is much easier.
var self = this;
this.shared_id;
$scope.getId = function () {
console.log(self.shared_id) ;
}
$scope.useId = function () {
console.log(self.shared_id) ;
}

how to pass values between functions in the same scope

I have 2 functions in the same controller and I am trying to pass the a value from one function to another. But I am getting an error TypeError: Cannot read property 'activeDataset' of undefined
Here is my code:
angular.module('daModule').controller("Controller1",Controller1);
Controller1.$inject = ['$scope', '$timeout'];
function Controller1($scope, $timeout) {
var ct = this;
ct.datasetName = "demo";
...
ct.activeDataset = function activeDataset(){
return ct.datasetName;
};
}
Here is my other function in the same file
function fn1(Controller1) {
...
var currentDataSet = Controller1.activeDataset();
...
}
Don't know where I am going wrong.
There are a couple of things going wrong here.
One is that the functions Controller1 and fn1 are being defined on the global name space. If another module were to use the same function names, there would be problems. We call this global name space pollution and it should be avoided.
The second problem is that in Controller1 the value of this is not defined until after the function is called. And when it is called, it is set to the local context of when it was called. Attaching properties to this in a function call does not make them available as a global property of the function. That is why you are getting "activeDataset undefined" in fn1.
To answer your question of how to pass values between functions in the same scope: The functions need to be inside the controller and they should put those values on the $scope.
angular.module("myApp").controller("myController", [$scope, myController($scope){
$scope.datasetName = "demo";
$scope.activeDataSet = function(){
return $scope.datasetName;
};
$scope.fn1 = function() {
return $scope.activeDataSet();
};
}]);

Angularjs: Databinding not working

Binding a service/factory variable within a controller works perfectly unless the factory variable is initiated through $http. Can anyone explain why?
NOTE: Since controller.someVariable = factory.someVariable doesn't work. Currently I am referencing the factory variable directly for manipulation as
factory.someVariable
Controller:
app.controller('SecondCtrl',function($scope,testFactory){
$scope.obj = testFactory.obj;
$scope.factory = testFactory;
$scope.jsonData = testFactory.jsonData; //Not Binding
//Accessing $scope.factory.jsonData works while $scope.jsonData doesn't
});
Factory:
app.factory('testFactory', ['$rootScope','$http',function ($rootScope,$http) {
var factory = {};
factory.obj = { 'name':'Jhon Doe'};
factory.jsonData;
factory.fromjson = function() {
$http.get("data.json")
.success(function(data){
factory.jsonData = data.result;
})
}
factory.fromjson();
return factory;
}]);
Plunker: http://plnkr.co/edit/wdmR5sGfED0jEyOtcsFz?p=preview
As I've mentioned in the comments, the reason this is occurring is because $scope.jsonData = testFactory.jsonData; is a value assignment, and unfortunately that value isn't available from the server yet when this assignment occurs. the other assignments work because they are reference assignments.
One quick but dirty way to solve this would be to declare factory.jsonData = {}; instead of factory.jsonData;. This would change the call to a reference assignment (object to object) and allow changes to one to propagate to the other.

How to add a function to all scopes..

I have a function on rootScope that I defined.
I later use it in controllers on the controller's scope - as it inherits the function from the rootScope.
now, I would like to do the same in directives with isolatedScopes.
since they don't prototypically inherit from rootScope, I need to find a another way to place that function on each isolated scope.
is there a way to customize isolated scope on creation, or some other hook?
update
Clarification: i need the function on the scope - not rootScope.
the reason is that we use this.$on('$destroy'...). so we basically want to execute code each time my scope is destroyed.
Current implementation: currently i override $rootScope.$new and check, if isolated i simply add the function on the scope. however this feels hackish and i would like to find a better solution.
here is my current code
$rootScope.registerTask = function(){
....
this.$on("$destroy", function() {
...
});
};
$rootScope.origNew = $rootScope.$new;
$rootScope.$new = function(isolate, parent ){
var newScope = this.origNew(isolate, parent );
if ( isolate ){
newScope.unregisterTask = ...;
newScope.registerTask = $rootScope.registerTask;
}
return newScope;
};
$rootScope.unregisterTask = ...;
Ahh.. the answer has been in front of me all along.. because the question was wrong!
All I wanted to do is assign functions on each and every scope (including isolated).
Well, scopes have prototypical inheritance, then just use that!
var Scope = Object.getPrototypeOf($rootScope);
Scope.registerTask = function(){
....
this.$on("$destroy", function() {
...
});
};
Scope.unregisterTask = ...;
should do the charm.. anywhere on load..
just goes to show - don't write code under pressure, you will work harder and get crappy results.. :)
I think you can inject the $rootScope in to the directive as,
app.directive('testDirective', ['$rootScope', function($rootScope) {
return {
scope : {},
link : function() {
},
controller : ['$scope', function($scope) {
$rootScope.rootScopeFunc();
}]
}
}]);
here is a DEMO

Adding function to controllers in AngularJs

I'm trying to add function to controller in angularJS, the way I think should be working but sadly not.
Here is my code.
//this is working.
$scope.adddata = function () {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
//this is not working
function adddata() {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
$scope.adddata = adddata();
Both functions above are in the definition of controller, hence $scope variable is available.
Can I only use $scope.functionname = functionname(){....}
or I can create a function and later assign it to controller / scope.
Do $scope.adddata = adddata; (no parentheses). Using the parentheses will assign the result of calling adddata() to the scope variable, which is undefined (adddata() does not return a value).
This would work:
$scope.adddata = adddata;
instead of:
$scope.adddata = adddata();
Don't invoke the function, pass a reference to it.

Resources