How to pass scope variable in ng-init using AngularJS - javascript

I have problem passing the variable declared from the scope to ng-init:
so far I have something like this:
$scope.x = '10';
<div ng-controller = "controller" ng-init="function(x)">
How do I pass x var from the scope inside ng-init function?

A lot of people will tell you you shouldn't do this (as mentioned in the docs here: https://docs.angularjs.org/api/ng/directive/ngInit).
As for actually doing it....
<div ng-controller="controller" ng-init="x = x">

Maybe this one can help you:
$scope.x = '10';
<div ng-controller = "controller" ng-init="x">

If you wanted to push a value in using the ng-init i would use something like this
Js code
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.x = "this will be replaced"; //not really needed
$scope.initialize = function(bar){
$scope.x=bar;
}
})
and html
<div ng-app="app" ng-controller="ctrl" ng-init="initialize('your value')">

If you want to execute a function on a tag where you have a controller, why not simply run the function in the controller's constructor (i.e. function)?
Not everything has to be in the markup.
JS:
angular.module(...).controller('MyController', function ($scope) {
$scope.myFunction($scope.x);
})
HTML:
<div ng-controller="MyController"></div>

Related

HTML load before my js function executes

If my controller, I have a function to set the true to a variable.
function setShow() {
return this.isShow === 'Foo';
}
My this.isShow is 'Foo'
In my template, I have <div ng-if = "vm.setShow()"> Hi </div>
But it seems like that HTML load before my js function executes? I do not know how to handle this case. I often face this problem.
You can try for this:
In angularjs:
But $timeout service should be inject into your controller.
$timeout(function(){
// write your logic here
},100);
This will fire when your HTML document is ready.
Call your function inside the timeout.
Or in JavaScript you can use the:
Settimeout(function(){
//write here
},100);
From ng-if:
The ng-if directive removes the HTML element if the expression
evaluates to false.
If the if statement evaluates to true, a copy of the Element is added
in the DOM.
your function doesn't evaluate to true and that is why the div isn't show. try returning true from the function.
Edit: now that you edited your post, the problem seems to be the function isn't in $scope and there is a strange vm in ng-if that probably shouldn't be there.
You don't have the setShow function declared in the $scope. I think the ng-if directive doesn't find the function and it interprets as false.
Try
angular.module("myApp", []).controller("myCtrl", function($scope) {
var isShow = "Foo";
$scope.setShow = function () {
return isShow == "Foo";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-if="setShow()"> Hi </div>
</div>

Why I can't see a $scope variable that was defined in a $scope function?

I have the following piece of code in angular
$scope.prepare = function(){
$scope.elems = [1,2,3];
};
$scope.action = function(){
var elem = $scope.elems[0]; //undefined
}
then, in my view, I use the directive ng-init="prepare()" and attach to a button the action function on click event
<button ng-click="action()">action</button>
Inthe action function the scope hasn't the elems array defined?
Can anybody tell me why this happen?
Thanks!
Since you are not showing the controller or the scope of the HTML where you are calling init() and action(), I can't even guess why you are having problems since the code you have posted works. This is a pluker proving that much: http://plnkr.co/edit/qMzPtJtp9t9CoNKkmWIc?p=preview
<div ng-init="prepare()"></div>
<input type="button" value="Call function" data-ng-click="action()" />
<p>Init Defined: {{elems}}</p>
<p>Function call: {{redefined}}</p>
$scope.prepare = function(){
$scope.elems = [1,2,3];
};
$scope.action = function(){
$scope.redefined = $scope.elems[0]; //undefined
}
With that said, you are not using ng-init() correctly. From the angluar documentation:
"This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat ... and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope."
Link to ng-init documentation: https://docs.angularjs.org/api/ng/directive/ngInit
You will be much better off initializing your array in the controller.

Using this instead of $scope inside controller

I am trying to follow style guide for angular and there wrote we should use this insted scope...
Styleguide
Could someone explain me when I am able to use this?
Here is my try..... What I am doing wrong?
I am trying to toggle form....
here is my html code:
REPLY
<a href="#" ng-click="formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>
With classic $scope I would do like this inside my conroller :
$scope.formEdit = function(data){
data.formEditShow = !data.formEditShow;
}
But with this it should look something like this(but don't work):
var vm = this;
vm.formEdit = formEdit;
function formEdit(data){
data.formEditShow = !data.formEditShow;
}
Anyone can help me to understand this?
When you are using this(context) in controller instead of $scope, you must use controllerAs while defining html on page to access controller variables. Whenever you wanted to use variable bounded to this on view you could use alias of your controller. Below you can see vm is alias of controller.
ng-controller="myController as vm"
Then while accessing controller method an variable inside ng-controller div you need to use alias of your controller like ng-click="vm.formEdit(x)"
HTML
REPLY
<a href="#" ng-click="vm.formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>
Assuming your controller is named FormController.
First step
The first step is to declare the route (or the ng-controller value if you are not using a router) as such:
FormController as form // name it semantically instead of a generic name
Due to the above configuration, angular will alias as form the instances of FormController.
HTML template
Then adapt your html template according to the alias you gave (form). I modified your html to keep only the essential part about the question. We are calling the functions form.reply and form.close.
REPLY
CLOSE
Controller declaration
According to what we wrote above, our controller should look like that:
myApp.controller('FormController', function () {
var vm = this;
vm.reply = function () {
// ...
}
vm.close = function () {
// ...
}
}
Notice the var vm = this; line? Theoretically we could get rid of this line, and store the functions reply and close in the this object. But depending of the context, this does not refer to the same object. In a callback function this would not refer to the controller but to the callback function. That's why we are caching the this that refers to the controller. We usually name this reference vm for viewmodel, as a controller controls a view.

Scope of a function inside an Angular JS Controller

What scope is a function defined inside an angular js controller, part of?
.controller('MyCtrl', ['$scope', '$location', function($scope, $location) {
function log() {
console.log('Vanakkam Ulagam');
}
var functionToCall = 'log';
????????[functionToCall]();
}])
I tried MyCtrl, this and $window. I can access the function by namespacing it like so functions.print = function() and then using functions[functionToCall]().
I am more interested in accessing the function without namespacing it. Is it possible? If not, why?
i think this is solution for this question
var f;
var a = angular.module('MyApp',[]);
a.controller('MyCtrl', ['$scope', function ($scope) {
$scope.log=function(){
console.log('test');
}
f=$scope.log;
});
and this function useable to element html for example
<button ng-click='log()'></button>
or
<button onclick='f()'></button>
If you're just trying to access global functions in your controller code, window (or $window if it's properly injected) should work fine:
$scope.alert = function(text) { window.alert(text) }
To be extra sure this works in other environments you could manually bind it in a self-invoking anonymous function:
(function(global){ //make the global scope assigned to the variable global
app.controller('MyCtrl',['$scope',function($scope){
$scope.alert = global.alert;
}]);
)(this); //this is the global object when this is evaluated
If you want to do anything inside an expression on a DOM element (such as ng-click), it's important to realise that angular expressions are evaluated by Angular's own expression evaluator (namely through $scope.$eval). So if something is not attached to a scope, it cannot be used in an angular expression.
However, if you were to do something like attach the global object to the scope, then everything is fair game. This really isn't recommended (I think there's no real reason to do this, and its better to manually define functions you need), but :
$scope.global = window
Inside your controller definition should work. You can then do things like ng-click="global.alert('Yo SO!')" in your DOM without issues.
For better testability you could use $window (you said you tried it and it didn't work... are you sure you injected it properly? Look at the example in the documentation carefully). But like I said, if you're attaching the global object to the scope you're opening Pandora's Box.

Object not a function in AngularJS

I have a controller that seems to be misbehaving. I have removed all the other code that works to make this short:
Controller:
'use strict';
angular.module('AppliedSiteApp').controller('CarouselCtrl', function ($scope) {
$scope.nextImage = function() {
console.log('hi');
}
});
View:
<div class="carousel" ng-controller="CarouselCtrl">
<ul class="nav">
<li ng-click="prevImage()"><</li>
<li ng-click="nextImage()">></li>
</ul>
</div>
Every time I click the button in the browser it says: 'TypeError: object is not a function' or 'no method replace'. What am I doing wrong?
Are you still having a problem with this?
I ran into the same issue. The problem for me was that the function name in the controller and view was the same name as a form I was using in the same view.
Changing either the form name or the function name fixed the error for me.
Something is wrong with the way you are wiring things I believe. I usually use this scaffold:
angular.module('AppliedSiteApp.controllers', []).
controller('CarouselCtrl', ['$scope', function($scope) {
$scope.nextImage = function() {
console.log('hi');
}
}]);
The first argument to controller is the name, and the second is an array. In the array, you define what services you are injecting into your controller, then you define the callback function with the injected services as parameters.
When creating a new module you need to specify a second parameter (its dependencies). If you have none, simply pass an empty array.
angular.module('AppliedSiteApp', [])...
Your example could access an existing module (that's when you don't specify the second argument), but then there's probably some code missing to spot the error (or I'm just blind).
try the following definition of controller
var AppliedSiteApp = angular.module('AppliedSiteApp', []);
function CarouselCtrl($scope) {
$scope.nextImage = function() {
console.log('hi');
}
}
I agree with the other responses that it's an issue with your wiring. Try this fiddle as an example: http://jsfiddle.net/reblace/7fVQR/
Declare your outer div like this:
<div ng-app="app" ng-controller="MainController">
And then your controller like this:
var app = angular.module('app', []);
function MainController($scope) { ... }

Categories

Resources