How can i pass scope in template in angular js - javascript

I have one BaseController with common functions which my all other controllers inherit .
The controller is like this
function BaseController () {
this.defaultFilters = {};
this.doStuff = function ($scope) {
$scope.myobj.value = 1;
this.otherfunction();
};
I inherit that in my controller like this
BaseController.call($scope);
Now in my do stuff function i need to pass $scope because myobj is only visible there.
Now i want to know that how can i pass that in my template because i want to call that function when some click on some button
ng-click="doStuff(scope)"

Everything that you associate with your controller's scope, so you just associate your scope with some variable and i guess that will do the job.
Something like this :
app.controller(function($scope) {
$scope.scope = $scope;
});
But if you go by some standard approach, i suggest moving these common functions inside some service, injecting this service into each controller and using it in the views.
Something like this :
app.service("constantService", function() {
this.data = {}; // This will represent your common data.
this.commonFunction = function() {
};
});
app.controller(function() {
$scope.constantService = constantService;
// You can now use $scope.constantService.data as your reference for data, and then can copy it to some local $scope variable whenever required.
});
ng-click="constantService.commonFunction()"

Related

How use prototypical inheritance in controllers in node.js

I need make one Super Function inherit the this of other function and make this other function inherit the methods from the Super Function, this is possible?
Explanation:
I have my BookingController and I want make the Controller function inherit the this.ME property:
BookingController.js:
var Controller = require('../api/Controller');
function BookingController() {
Controller.call(this);
this.ME = 'something here';
}
BookingController.prototype = new Controller;
BookingController.constructor = BookingController;
Controller.js:
function Controller() {
console.log(this); // EMPTY
};
Controller.prototype.myMethod = function() {
// Should work if BookingController try to access.
}
But nothing happens, there is no error and the BookingController can't find my myMethod and my Controller can't my this.ME
You use a bit wrong inheritance model. I suggest you to use something like
BookingController.prototype = Object.create(Controller.prototype);
BookingController.prototype.constructor = BookingController;

Angular calling a parent method from an extended controller

I been spinning on this for days with no luck. I have BaseController with an init method among other things. I then wish to extend this controller and call the parents 'init' method from within the childs 'init' method.
The general answer for this is to call $scope.$parent.init($settings_object). However this is returning Error: $scope.$parent.init is not a function.
Generally the extended controller works fine being able to access the perents function and settings without issues. Just this example calling the same parent method from the child fails.
BaseController
(function( ){
var mainApp = angular.module("MyAppModule");
mainApp.controller('BaseController',function($scope, $rootScope,GLOBAL_CONFIG, ajaxRESTful,sharedValues, messageDisplay) { //base contorller
var bvm = this; //base vm
this.init = function($settings_object){
var keys = Object.keys($settings_object);
for(i=0;i<keys.length;i++){
bvm[keys[i]] = $settings_object[keys[i]];
}
}
//code remved to keep simple
});
})();
Extended controller
(function( ){
var app = angular.module('MyAppModule');
app.controller('RoleEdit', function($scope, $rootScope,$controller) {
angular.merge(this, $controller('BaseController', {$scope: $scope}));
var vm = this;
vm.newRoleFormData = [];
vm.role_id = null;
vm.mode = 'create';
vm.role = null;
vm.init = function ($object) {
console.log(vm);
console.log($scope.$parent);
$scope.$parent.init($object);
if(vm.role_id != null){
vm.loadInRole( );
}
};
}) //end contoller
})();//end of app
Why doesn't this work?
Is there a better way to do this?
The controller object (this) and the $scope object aren't directly related. There is no automatic wiring between them. $scope.$parent doesn't return a controller, it returns the parent scope. And since you registered your parent method in this.init instead of the usual $scope.init, you can't expect to find it using scopes.
You may circumvent this in a great number of ways, but as others have suggested, if you have functionality that is shared by many controllers, try to put it in a service instead. Maybe your BaseContoller itself should be a service.
You should do:
var parentInit = this.init.bind(this);
this.init = function ($object) {
parentInit($object);
if(vm.role_id != null){
vm.loadInRole( );
}
}

How to call a factory method dynamically coming from variable?

I have a service which will return the name of factory. I already injected all the factories into controller. I need to use the variable to call the method inside that factory. I know i can use
if(var == 'factoryname') {
factoryname.method()
}
but i don't want those if conditions because i have number of factories. Is there any way to call a method inside that factory like in java script
window[var]
You should consider storing all of your factories on an object:
var factories = {
factoryA: { method: function() {} },
factoryB: { method: function() {} },
};
var factory = 'factoryA';
factories[factory].method();

How to have a value passed to scope from outside the controller?

I am new to angular world and I have function which is loading the html inside perticular div on load and then controller gets initialize. I want to make single var available inside the controller so wondering if it's possible to assign that var to scope from outside the controller.
//controller
var cntlrs = angular.module('MyModule');
cntlrs.controller('ControllerTest', function ($scope, $http) {
//want to have var available here from $scope
});
//accessing scope from outside
var appElmt = document.querySelector('[ng-app=MyApp]');
var $scope = angular.element(appElmt).scope();
var customer = "New Customer";
//how can I set customer value inside scope?
I would suggest reading the angular docs more. $scope is your model (or probably the term ViewModel is more appropriate).
To get values into your controller, I would recommend a factory or a service. One can call setCustomer on the factory, then other controllers would be able to see that value using getCustomer.
var mod = angular.module('MyModule', []);
mod.factory("CustomerFactory", function () {
var customer;
return {
getCustomer: function () {
return custData;
}
setCustomer: function (custData) {
customer = custData;
}
}
});
mod.controller("TestController", function ($scope, $http, CustomerFactory) {
$scope.customer = CustomerFactory.getCustomer();
}
It might also be better if you weren't referencing $scope outside of angular (i.e. from angular.element(...).scope()). I don't know what you are trying to solve, but it seems like from the code above, all that logic can be put inside the controller.
Yes, from outside the controller you can target an element that is within your angular controller:
var scope = angular.element("#YourElementID").scope();
And now you will have access to everything on the scope (Just as if you were using $scope)
I decided to work like this, and it seems to be allright!! It does not require a big effort, the only boring part is that in the template you need always to use vars.somepropertyormethod
//an outside var that keeps all the vars I want in my scope
var vars = {
val1: 1,
val2: "dsfsdf",
val3: function() {return true;}
}
//and here I set the controller's scope to have ONLY vars and nothing else:
angular.module('myModule', [])
.controller('myControllerOpenToTheWorld', function($scope) {
$scope.vars = vars;
});
With this, I can set vars.anyproperty from anywhere I want. The trick is that the real values are all wrapped inside an object, so as long as you don't reassign the wrapper vars, you can access it from both outside and inside:
//change val2
vars.val2 = "new value changed from outside";
In the markup, it would work like this:
<div>{{vars.val1}}</div>
<div ng-if:"vars.val3()">{{vars.val2}}</div>

How to create helper class that can accessed with controller on AngularJS

how can I create a helper/utility class that can be accessible from the multiple controllers?
For example, I have two controllers: UpdateItemCtrl and CreateItemCtrl. These have common functions inside which increases redundancy and lowers managability.
I'd like to create a ItemSaveHelper class which I would put the common methods inside and call them from the active controller.
You want to create a service.
A service is just a singleton that can be injected into different things to provide modular/shared functionality. Here's a simple example: http://jsfiddle.net/andytjoslin/pHV4k/
function Ctrl1($scope, itemManager) {
$scope.addItem = function(text) {
itemManager.items.push(text);
};
}
function Ctrl2($scope, itemManager) {
$scope.items = itemManager.items;
}
app.factory('itemManager', function() {
return {
items: []
};
});

Categories

Resources