I have a template like this.
<body ng-app="demo" ng-controller="demo">
<div ng-include="/main.html">
</div>
</body>
And the main.html is.
<div ng-app="main" ng-controller="main>
""
</div>
here is the js.
JS-1
var myapp = angular.module('demo', []);
myapp.controller('demo', function($scope,$routeParams, $route,$http) {
$scope.variable="444"
})
JS-2
var mainapp = angular.module('mainapp', []);
myapp.controller('main', function($scope,$routeParams, $route,$http) {
})
Is it possible to access the scope of JS-1 inside JS-2?, if yes how, if no is there any solution to this.Thanks.
It depend what you want to do.
If you want read $scope.variable variable from JS-1, you should see it in JS-2 $scope.
If you want modify $scope.variable form JS-1, you should create method in JS-1:
$scope.changes = function(data){
$scope.variable = data;
}
This method also should be available in JS-2 $scope.
This isn't nice solution but should work.
The best solution is to create service which will provide operations on JS-1 fields.
Related
I'm trying to develop a solution through AngularJS where when the user changes the profile image, all other photos based on their profile are also changed.
How can I start developing this feature?
Thanks in advance!
[Solution]
With the help of the #wolfman6377, I can understand the functionality and develop the solution for what I need. I'll leave an example in CodePen.
CodePen
var myApp = angular.module('myApp',[]);
myApp.controller('myController', function() {
this.myVar = 'https://robohash.org/asd'
this.updatePicture = function() {
this.myVar = 'https://angular.io/resources/images/logos/angular/angular.png';
};
});
Thank you, #wolfman6377.
You are using a jQuery-like strategy. jQuery element selector will not be able to change the value of myVar.
I would recommend going through some basic tutorials on angular1. But in a nutshell, you need to:
Do not grab elements and change attributes
add a module to the ng-app value
Use ng-controller in the template
Add ng-click to the button to update the value of myVar
template
<body ng-app="myApp">
<div id="var" ng-controller="myController as vm">
<img ng-src={{vm.myVar}} />
<button ng-click="vm.updatePicture()">Click me</button>
</div>
</body>
controller:
angular
.module('myApp', [])
.controller('myController', function() {
this.myVar = 'https://www.w3schools.com/angular/pic_angular.jpg'
this.updatePicture = function() {
this.myVar = 'https://angular.io/resources/images/logos/angular/angular.png';
};
});
So, here's a sample code:
<div ng-controller="MyControllerOne">
<span ng-click="foobar()">Click Me!</span>
</div>
Can I, from that template, without changing controller, call the function foobar() in MyControllerTwo:
.controller('MyControllerOne', function($scope) {
//some code
})
.controller('MyControllerTwo', function($scope) {
// method I wanna call
function foobar(){
}
})
While not the prettiest solution, it is technically possible...ish.
If you update your HTML to:
<div ng-controller="MyControllerOne">
<span ng-controller="MyControllerTwo as mct" ng-click="mct.foobar()">Click Me!</span>
</div>
Then you should get your expected results.
You can call method which is in another controller from the template by injecting '$controller' service in the controller. Below is the demo and code.
You can see demo here: http://plnkr.co/edit/oBEKxamgJv0uDVsJJwth?p=preview
HTML:
<body ng-controller="MainCtrl">
<div ng-click="fooBar()">Click Me!</div>
</body>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('SubCtrl', {$scope: $scope});
});
app.controller('SubCtrl', function($scope) {
$scope.fooBar = function() {
alert('second controller');
};
});
Pretty old question, but if any one is still looking for an alternative answer ...
It should be possible to use $emit or $broadcast.
Like from ControllerOne :
$rootScope.$broadcast('callToFoobat',{});
And then from ControllerTwo :
$scope.$on('callToFoobat', function(){
// whatever you want, so why not a call to foobar
})
Just a rough solution. Might be more elegant or lighter than just $rootScope.$broadcast. And maybe think about stoping propagation whenever needed.
I am learning angularjs and I am trying to use the controllerAs syntax as I am from Java background and this would make more sense to me but I am having trouble understanding the digest loop.
I am trying to do a http call and update the variable in the controller.When I am using $scope in controller the view is updated after the data is received but when I am using the controllerAs syntax the view is not updated.
Codepen with $scope Syntax
http://codepen.io/eternal15/pen/BzANEw?editors=1111
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
</head>
<body ng-app="Test" ng-controller="testCtrl">
{{output}}
<button ng-click="onClick()">Test</button>
</body>
</html>
//JS FILE
angular.module("Test", []).controller('testCtrl', ['$scope','$http', function($scope, $http){
$scope.output = "Loading";
$scope.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
$scope.output = "worked!!";
console.log($scope.output);
})
}
}]);
Codepen with controllerAs Syntax (View not updated)
http://codepen.io/eternal15/pen/yJKoaZ?editors=1011
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
</head>
<body ng-app="Test" ng-controller="testCtrl as test">
{{test.output}}
<button ng-click="test.onClick()">Test</button>
</body>
</html>
//JS File
angular.module("Test", []).controller('testCtrl', ['$http', function($http){
this.output = "Loading";
this.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
this.output = "worked!!";
console.log(this.output);
})
}
}]);
I have read about the controllerAs syntax and I think it would add the object (test in the example above) under scope and thus the variables are accessible using (test) object.
So the digest loop runs after $http call because the view is updated in the first example using $scope. Since the digest loop is executed the object test in the second example should also be updated right?
Also i tried to inject $scope and do $scope.$apply() and that also didn't work and it gave me this error
Error: [$rootScope:inprog] http://errors.angularjs.org/1.5.2/$rootScope/inprog?p0=%24digest
I would like to know what I am doing wrong. Although i could go back to using the $scope format, I would like to know if I am doing something wrong or should I add other statements to watch the variables and update the values manually.
Thanks in advance
this has a different meaning inside function. Assign this to a variable and use it. Try:
angular.module("Test", []).controller('testCtrl', ['$http', function($http){
var vm = this;
vm.output = "Loading";
vm.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
vm.output = "worked!!";
console.log(vm.output);
})
}
}]);
This is because of javascripts closures. When defining a new function you're creating a new scope, hence the keyword this has a new meaning for each new scope.
To solve this, define the controllers scope at the top of your controller. Common names used are either vmor $ctrl.
Your controller would then look somehting like this:
angular.module("Test", []).controller('testCtrl', ['$http', function( $http){
var $ctrl = this;
$ctrl.output = "Loading";
$ctrl.onClick = function(){
console.log('clicked');
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(data){
$ctrl.output = "worked!!";
//$scope.$apply();
})
}
}]);
I'm trying to understand why I must use the as in order that the two-way binding will work with this inside a controller.
working example:
<div ng-controller="MyController as TestController">
{{TestController.test()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function(){
this.test = function test(){
return "test";
};
});
</script>
not working example:
<div ng-controller="MyController">
{{MyController.test()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function(){
this.test = function test(){
return "test";
};
});
</script>
If you want to use this in your controllers you need to use the controller as syntax otherwise you have to use $scope in your controllers. If you didn't use controller as the controller would need to be:
app.controller('MyController', function($scope){
$scope.test = function test(){
return "test";
};
});
and the view would need to be:
<div ng-controller="MyController">
{{test()}}
</div>
One of the benefits of the controller as syntax is it helps to promote the use "dotted" object in the View which helps to avoid any reference issues that may occur without "dotting". For more info on scope reference issues take a look at this post
Not really an answer to your question, but normally you'd define functions you want to invoke from the DOM on the Controller's $scope.
Example:
<div ng-controller="MyController">
{{test()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('MyController', function($scope){
$scope.test = function test(){
return "test";
};
});
</script>
http://plnkr.co/edit/lbgG9MCJ1kNBhArLpEpc?p=preview
Edit: Sorry, forgot to update the code in my post. The plnkr should've been right all along though.
Thanks to Wayne Ellery:
It's because Angular added the controller as syntax in 1.2 which enables you to work with this. ng-controller="MyController as myController". Think of it as var myController = new MyController();. It's essentially scoping an instance of MyController to myController.
in my app I have a wrapper controller that handles some properties dynamically based on other-controllers within it. everything works like a charm if the other-controllers are present/static on load, but as soon as I'm trying to make them dynamic, they stop working.
It was my understanding that the $rootScope is available from everywhere within the app, is that not true?
my JS looks like this:
var webApp = angular.module("webApp",[]);
webApp.controller("ControllerA", function($scope, $rootScope){
$rootScope.cnt = 0;
$rootScope.cntPlusPlus = function(){
$rootScope.cnt++;
};
$rootScope.controllerBs = [];
var template = $(".controller-b").html();
$scope.addControllerB = function(){
$rootScope.controllerBs.push(template);
};
});
webApp.controller("ControllerB", function($scope, $rootScope){
$scope.cntPlusPlus = function(){
console.log("overwrite plus plus");
}
});
Full example: http://plnkr.co/edit/tAcv1F9y7t9q9XsQ1EFL?p=preview
I know that this would be probably better with directives, but is there any way to make it work with Controllers?
thanks for the help
Don't try to access the DOM from controller code. Never. It is very bad practice which breaks AngularJS conventions and eventually provides you with bad architecture. This also means you should not create any DOM elements manually from a controller.
Better to manipulate with the scope itself, not with its visual representation. You can add new models to scope on your button's click, which will be translated to new elements by ng-repeat directive, each with its own controller (remember controllers are instances, not singletons, so that they have separated life cycles).
You might want to make use of <script type="text/ng-template"> and ng-include here instead of hidden divs.
Try to avoid using $rootScope when possible - it is global state which can be dangerous.
It might look like this then (plunker):
HTML:
<div class="controller-a" ng-controller="ControllerA">
Controller A
<div>
<button ng-click="cntPlusPlus()">cnt++</button> CNT: {{cnt}}
</div>
<button ng-click="addB()">Add B</button>
<div ng-repeat="B in Bs">
<div ng-include="'b-template'"></div>
</div>
</div>
<script type="text/ng-template" id="b-template">
<div ng-controller="ControllerB">this is controller b: <button ng-click="cntPlusPlus()">cnt++</button></div>
</script>
JS:
var webApp = angular.module("webApp",[]);
webApp.controller("ControllerA", function($scope){
$scope.cnt = 0;
$scope.cntPlusPlus = function(){
$scope.cnt++;
};
$scope.Bs = [];
$scope.addB = function(){
$scope.Bs.push({});
};
});
webApp.controller("ControllerB", function($scope){
$scope.cntPlusPlus = function(){
console.log("overwrite plus plus");
$scope.$parent.$parent.$parent.cnt++; //should be moved to service
}
});
</script>