AngularJS controller function never called - javascript

My angularjs controller function is never called. I see all the js files included in my sources, it's just not ever hitting the initialization of my controller. What is wrong with this code?
eventListCtrl.js:
eventsApp.controller('eventListCtrl', ['$scope', function ($scope) {
// this code is never called
alert('controller initializing');
$scope.name = "Test";
}]);
app.js:
'use strict';
var eventsApp = angular.module('eventsApp', []);
Index.cshtml:
<div ng-controller="eventListCtrl">
<div class="row">
<div class="spann11">
<h2>{{name}}</h2>
</div>
</div>
</div>
<script src="/scripts/vendor/angular.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers/eventListCtrl.js"></script>

You need to do this
<html ng-app="eventsApp">
So you actually activate the module

I want to post my issue/resolution here in case anyone does the same thing as me.
<div ng-controller="coolCtrl" ng-if="VAR">
I was trying to init a controller on an element that didn't get created (because of the ng-if="var" )
facepalm

Wild guess:
angular.module('eventsApp').controller('eventListCtrl', ['$scope', function ($scope) {
// this code is never called
alert('controller initializing');
$scope.name = "Test";
}]);
in your controller file?

<html ng-app="eventsApp">
<div ng-controller="eventListCtrl">
<div class="row">
<div class="spann11">
<h2>{{name}}</h2>
</div>
</div>
</div>
<script src="/scripts/vendor/angular.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers/eventListCtrl.js"></script>
</html>
This should fix it

Related

Accessing JSP variable from javascript [Angular JS]

I am working with angular JS and JSP. i need to retrieve the session attribute variable from the JSP to my controller. My code is below
JSP
<html lang="en" ng-app="myApp">
<body>
<div data-ng-controller="myCtrl as vm" style="height:100%">
<md-content layout="row" style="height:100%">
<div class="widget">
<h2>Header</h2>
<div ui-view></div>
</div>
</md-content>
</div>
<script type="text/javascript" src="/root/script/script.js"></script>
<%
String policy = session.getAttribute("POLICY_CHANGE");
%>
</body>
</html>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
// i want to get the JSP variable here
});
Set session value to hidden input.
<div data-ng-controller="myCtrl as vm">
<input type="hidden" id="sessionData" />
</div>
<script>
var data = '<%=request.getSession().getAttribute("POLICY_CHANGE")%>';
document.getElementById("sessionData").value = data;
</script>
and get value
app.controller('myCtrl', function($scope, $document) {
$scope.data = $document[0].getElementById("sessionData").value;
console.log($scope.data);
});
You can output the variable using expression language as a data attribute, like this:
<div data-my-variable="${myVariable}" id="myDiv"></div>
And if you are using Jquery, you can use the attr function:
var output = $("#myDiv").attr("data-my-variable");
Try (I've never tried this - just and idea... please post if it is working):
<script>
angular.module('jspVariablesService', [])
.value("valueName",${yourVariable});
</script>
in <head></head> or at the beginning of body and then import jspVariableService in
var app = angular.module('myApp', ["jspVariableService"]);
and use it in controller:
app.controller('myCtrl', ["$scope", "valueName" function($scope,valueName) {
//use your value!
});

AngularJS tutorial not binding data

I have a very basic example that isn't working: I have two aspects, the index.html and the main.js. They are in the same folder:
<!DOCTYPE html>
<html>
<head>
<title> AngularJS Tutorials </title>
<link rel="stylesheet" href="css/foundation.min.css">
<script src="main.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<h1>{{data.message}}</h1>
</div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
</body>
</html>
main.js
function FirstCtrl($scope) {
$scope.data = {message: "Hello"};
}
my page shows this:
{{data.message}}
You need to add the controller to the angular module. you can use the controller function to add the js function for your controller.
var FirstCtrl = function FirstCtrl($scope) {
$scope.data = {message: "Hello2"};
};
angular.module("myApp",[]).controller("FirstCtrl",FirstCtrl);
If you already had the angular module defined somewhere else in the page, Use this version.
angular.module("myApp").controller("FirstCtrl",FirstCtrl);
Here is a working sample http://jsbin.com/tiroteharu/edit?html,js,console,output
<script src="~/Scripts/angular/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', ['$scope', function ($scope) {
$scope.data = { message: "Hello" };
}]);
</script>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<h1>{{data.message}}</h1>
</div>
</div>
More help read: https://docs.angularjs.org/guide/controller

Calling an AngularJS controller function from outside of it

I have the following code:
app.controller('MatrixExpertCtrl', function($scope,$http){
$scope.PassedMatrix=[];
$scope.GetMatrixFromServer=function(){
$http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
alert("The matrix grabbed from the server is: " + resp[0].ans);
$scope.PassedMatrix.push(resp[0].ans);
});
};
$scope.DispSize=function(){
alert("testing");
alert("The size is "+$scope.PassedMatrix[0].size) ;
};
//$scope.GetMatrixFromServer();
});
Now, suppose, in HTML, I have something like this:
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="text-center">
<h3>Example Survey</h3>
<p>example paragrah</p>
<p>More random text</p>
<p>ending the paragraphs</p>
<button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>
</div>
//Much more code
<div id="body2">
<div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">
<div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">
<div class="text-center">
Meaning with this:
Is it possible to call a function that is defined inside a controller, from outside of the scope of that same controller?
I need this because the function is manipulating a shared object, owned by the controller in a very very simple fashion (for example, clicking on the button changes the color of a given element).
I am having trouble to make this work, any help will be appreciated.
I think that declaring some data structures as global would help me solving this problem, but, I would like to avoid doing that because, besides it being bad practice, it might bring me more problems in the future.
If i understand your problem correctly than what you basically do have is one utility function which will work on your shared object and do your useful things (i.e. clicking on the button changes the color of a given element) and now you do require the same behaviour in another controller outside of it's scope. You can achieve the same thing in 2 different ways :
1).Create a service and make it available in your controllers like this :
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
changeColour: function() {
alert("Changing the colour to green!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.callChangeColour = function() {
myService.changeColour();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callChangeColour()">Call ChangeColour</button>
</body>
</html>
Pros&Cons: More angularistic way, but overhead to add dependency in every different controllers and adding methods accordingly.
2).Access it via rootscope
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalChangeColour = function() {
alert("Changing the colour to green!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalChangeColour()">Call global changing colour</button>
</body>
</html>
Pros&Cons: In this way, all of your templates can call your method without having to pass it to the template from the controller. polluting Root scope if there are lots of such methods.
try removing semicolon
ng-click="DispSize()"
because it binds ng-click directive to the function.

Angular JS - Load a template html from directive on click of a button

I am trying to load a HTML template when a link is clicked. I have made a directive that contains templateUrl which loads a HTML file. I am calling a function when a link is clicked that appends a div with our custom directive "myCustomer" to a div already in index.html. whatever i have done so far is shown below, but it doesn't work.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example12-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller">
show
<div id="d"></div>
</div>
</body>
</html>
script.js
(function(angular) {
'use strict';
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.showdiv = function(){
$("#d").append("<div my-Customer></div>");
};
}])
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html'
};
});
})(window.angular);
my-customer.html
<p>DIV CONTENT</p>
Here is the link i was testing this code here
This is because the angular doesn't bind the directives if you append content like this,
you need to $compile service to do this and this will bind the directives against your $scope
so controller like,
.controller('Controller', ['$scope', '$compile', function($scope, $compile) {
$scope.showdiv = function(){
var compiledeHTML = $compile("<div my-Customer></div>")($scope);
$("#d").append(compiledeHTML);
};
}])
here is the DEMO
OR good to do like this,
use ng-if to create or removing element from html,
try this code
Controller,
....
$scope.anableCustomerDirective = false;
$scope.showdiv = function(){
$scope.anableCustomerDirective = true;
};
HTML
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller">
show
<div id="d">
<div my-Customer ng-if='anableCustomerDirective'></div>
</div>
</div>
</body>
Suggestion
if your main intention is to place a html content after the click, then you can use ng-include here and it will much cleaner and no need of a another directive.
<div id="d">
<div ng-include="templateURL"></div>
</div>
$scope.showdiv = function(){
$scope.templateURL = 'my-customer.html';
};
find the DEMO
Seems like directive is only meant to load template from it.I'd suggest you to use ng-include directive then
Markup
show
<div id="d"></div>
<div ng-include="showDiv ? 'my-customer.html': ''">
The most common way is to use $compile. More info: Dynamically add directive in AngularJS
Then your controller may look like this:
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', '$compile', function($scope, $compile) {
$scope.showdiv = function(){
var el = $compile( "<div my-customer></div>" )( $scope );
$('#d').append( el );
};
}]);
Note that the directive invokation should look like this: <div my-customer>, not <div my-Customer></div> as you have in your code.
when you do it manually with append you actually do not run $apply or $digest so the directive is not run,
can you try to do it with ng-show or ng-if ... e.g
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller">
show
<div my-customer ng-if="showdiv"></div>
<div id="d"></div>
</div>
</body>
this way angular runs the $apply and the directive will be rendered.

Bootstrapping multiple angular apps on a page causes the error of controller undefined

I have two angular apps on my page. First one is bootstrapped using the "ng-app" directive that is on the main body. Second app is initialized manually using angular.bootstrap method.
First app that is automatically bootstrapped
<body ng-cloak ng-app="app">
<section id="mainbody">
<div class="container radar-main-container">
#RenderBody()
</div>
</section>
Below is the app.js for the main app
var commonModule = angular.module('common', ['ui.router']);
var appMainModule = angular.module('app', ['common']);
Second app that is manually bootstrapping
#section footerScript {
angular.bootstrap(document.getElementById('signup'), ['signupApp']);
}
Html
<div id="signup" ng-app="signupApp" ng-controller="SignupController">
<div ui-view></div>
</div>
Controllers created in the second module:
signupModule.controller("SignupController", ['$scope', '$location',
function($scope, $location, $window) {
}
signupModule.controller("PackageInfoController", ['$scope', '$location',
function($scope, $location) {
}
When I run this code I get the error "SignupController" is not a function got undefined and it takes me to this link Error
Maybe this helps you out, since it works perfectly fine.
HTML template
<!DOCTYPE html>
<html>
<head>
...
<script src="app.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="AppCtrl">
main
</div>
<div id="signup" ng-controller="SignupCtrl">
signup
</div>
<script>
// #section footerScript
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('signup'), ['signup','common']);
});
</body>
</html>
app.js
var common = angular.module('common', []);
var app = angular.module('app', ['common']);
app.controller('AppCtrl', function($scope) {});
var signup = angular.module('signup', ['common']);
signup.controller('SignupCtrl', function($scope) {});
First of all,Your apps must not be nested (one inside another).You applications must be out it and not on body tag.
The second thing is,that you can use ng-app in you html file only one time.

Categories