I have a simple angular snippet
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
$scope.age = "26";
$scope.height = "5.9";
$scope.gender = "M";
});
</script>
As you can see I have 4 variables declared in my myCtrl controller
$scope.name = "John Doe";
$scope.age = "26";
$scope.height = "5.9";
$scope.gender = "M";
Is there a way to programmatically list of all the declared $scope variables of a specific angular controller?
Why am I trying to do this ?
Sometimes, when you’re deep in 1000 lines of code in an angular controller, it will be very helpful to know what are the available variables to use at that specific moment. First, the benefit would be, so we don’t re-declare something that already been declared, and second, so we don't override an existing variable unintentionally. For those 2 reasons alone, that's why I am trying to list all the available $scope variables, especially the one that I declared in on that specific page, or in a specific controller of Angular.
NOTE : I am NOT looking to list all JS scope variables, but only looking for those one that I declared in Angular
I know exactly what you need and I use this lib extensively to show me my objects like Chrome does.
Angular json formatter
And the beauty is that it updates instantly with Angular magic. So you know the current state of your object at all times!
Simply drop this directive in your html and assign $scope to it.
Related
I'm trying to follow John Papa's guidelines, in which he explains how using this combined with controllerAs is preferable to $scope.
The problem is that I can't find an easy way to get a variable (user) defined in ParentController (vm.user) and use it, even transform it in a ChildController.
Code for illustration :
controllers.js
app.controller('ParentController', function() {
var vm = this;
vm.user = {firstName:"John", lastName:"doe"};
});
app.controller('ChildController', function() {
var vm = this;
/* How can I access 'vm.user' defined in ParentController
without using $scope as John Papa's suggests ? */
});
index.html
<div ng-controller="ParentController as parent">
<div ng-controller="ChildController as child">
</div>
I could just put everything in one big controller but I want to keep my code clean and readable.
Thanks!
You shouldn't access data from one controller to another, it's not a good practice. In order to share data between controllers, you should use a service.
Here you have JSBin with an example.
In my mine file I have the div with ng-view and it is loaded with the some template. Inside the temp`late I have a button which will change the value.
after to click the button, I am trying to show the value in the index but I recieving a null value.
In index.html I could have something like:
<html>
...
<body ng-app="productsApp" ng-Controller="mycontroller">
<div ng-view></div>
{{value}}
</body>
</html>
In my controller I have something like
angular.module('productsApp').controller('ProductController',
['$scope', 'dataService', function ($scope, dataService) {
$scope.value;
$scope.button = function () {
$scope.value= "123";
};
}]);
The template could be something like:
<button ng-click="button">CHANGE</button>
How can I assign values to main page from templates and show them?
You need to beware which controller you set, the names have to match. Also beware of typos, even when typing fast ;). Also look into the function call. You forgot to use () at the end. And naming things a little bit better would be recommended to (I don't say my namings are the best, but calling a function button is not very readable).
HTML
<body ng-controller="MainCtrl">
<p>Value {{value}}!</p>
<button ng-click="btnPressed()">Change</button>
</body>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.value = "456";
$scope.btnPressed = function() {
$scope.value = 123;
}
});
The controllers name in this example is MainCtrl. You need to refer the correct name as well in your HTML (you mix mycontroller and ProductController).
Working Plnkr
http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2
You have defined $scope.button in ProductController which set $scope.value.
But this $scope.value is come under scope of ProductController and not available under scope of mycontroller which parent scope.Thats why you getting null value.
Define $scope.value and $scope.button in mycontroller.
Or better way is define this functionality in some factory and access it wherever needed.
Or define that function and variable in $rootScope like
$rootScope.value;
but it make this global.
or define like this
$scope.$parent.value;
I got a variable in my angularjs scope like this:
function MyCtrl($scope) {
$scope.myvar = "{{'i want to translate this' |translate}}" + "{{' and this' |translate}}" + " but not this" ;
}
The translate is a custom filter which translates to french.
In the html:
{{myvar}}
I want to display "myvar" in the html but it displays the '{{' & '}}'.
I made a jsfiddle here
As per your jsfiddle code:
<div ng-controller="MyCtrl">
{{myvar}}
</div>
You've not used ng-app="myApp" directive anywhere. So angular know that which part of the HTML it need to bootstrap as angular app.
Another thing, you must avoid using global functions as controllers. Instead use
angular.module("myApp", [])
.controller("MyCtrl", MyCtrl);
Still you can't have
{{'i want to translate this' |translate}}" + "{{' and this' |translate}}
in your controller. instead you must use $filter and do the filtering in controller and just return the string.
$scope.myVar = $filer("translate")("i want to translate this") + $filer("translate")(" and this");
Inject $filter to your controller.
So, to start I have added some code to your jsfiddle and got it working. It renders your myvar.
var myApp = angular.module('myApp',['controllers']);
var controllers = angular.module('controllers', []);
controllers.controller('MyCtrl', ['$scope', function ($scope) {
$scope.myvar = "{{'i want to translate this' |translate}}" + "{{' and this' |translate}}" ;
}]);
Also see jsfiddle.
You can find a "working" fiddle based on the good advice from #mohamedrias here. By "working" I mean ng-app is properly declared in the html and your bindings are working. I agree with the advice already shared. Apply your filter logic within the controller. Then you could set the result to something like vm.myTranslatedVar and bind to that in your html with {{ vm.myTranslatedVar }}. vm simply stands for "view model" and sets your controller's scope rather than using $scope.
I'm learning angular.js, and wonder when app.controller("MyCtrl",...) should be used and when function MyCtrl($scope){...} should be used.
I see no big differences between the two approaches in this example (link to a plunker):
index.html:
<body ng-app="myApp">
<div ng-controller="FirstCtrl as app1">
<button class="btn" ng-model="app1.count"
ng-click="app1.increment()">
Click to increment</button>
{{ app1.count }}
</div>
<div ng-controller="SecondCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<script type="text/javascript" src="example.js"></script>
</body>
example.js:
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function () {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
}
});
function SecondCtrl($scope){
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
}
The major reasons for using the module based controller declaration are
Support for minification. The second approach breaks when you minify the code as Dependency Injection fails.
JavaScript good practice is to minimizing polluting the global namespace and the first syntax help there.
In both of your usages, the recommended approach is to inject $scope and use that (rather than using this, which you can do in the second approach as well).
The difference between approach one and two is in how to support minification. In the former, you can supply an array of injected arguments, whereas in the latter you modify $inject. This is of course a bit technical but it is highly recommended to support minification. See A note on minification in the documentation.
The former also does not name the function in the global scope, which is generally a good thing!
Typically, when you create an application you need to set up an initial state for an Angular scope.
Angular applies (in the sense of JavaScript's Function#apply) the controller constructor function to a new Angular scope object, which sets up an initial scope state. This means that Angular never creates instances of the controller type (by invoking the new operator on the controller constructor). Constructors are always applied to an existing scope object.
You set up the initial state of a scope by creating model properties. For example:
function GreetingCtrl($scope) {
$scope.greeting = 'Hola!';
}
The GreetingCtrl controller creates a greeting model which can be referred to in a template.
NOTE: Many of the examples in the documentation show the creation of functions in the global scope. This is only for demonstration purposes - in a real application you should use the .controller method of your Angular module for your application as follows:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingCtrl', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Note also that we use the array notation to explicitly specify the dependency of the controller on the $scope service provided by Angular.
For more detail Read this
UPDATE: angular 1.3.0-rc4 removed $scope.this see commit
Each instance of a $scope has a property named this that points back to itself.
Currently (1.2.0rc1) it's not prefixed with $(public/protected) or $$(internal) so it doesn't hint that it's an angular specific property.
What is the use case for it?
This question had me grepping all through the codebase for an explanation; I finally got a hint from an old test.
Since AngularJS expressions are evaluated in the context of a scope, the scope needs to have a property called this that refers to itself so that expressions that contain this work. Take the following example:
<div ng-controller="FirstController">
`this.num` (with normal scope): {{this.num}}
</div>
<div ng-controller="SecondController">
`this.num` (with scope.this removed): {{this.num}}
</div>
app = angular.module('myApp', []);
app.controller('FirstController', function($scope) {
$scope.num = 10;
});
app.controller('SecondController', function($scope) {
delete $scope['this'];
$scope.num = 10;
});
The second example does not work; see http://jsfiddle.net/BinaryMuse/mzbpz/ for a demonstration.