Controller Function is not getting called on ng-click - javascript

This is my View Code
<div ng-controller="signupCtrl">
<ul class="list-group" >
<li class="list-group-item">
<div class="form-group">
<input type="text" ng-model="signupCtrl.firstName">
</div>
...
</div>
<div class="form-group">
<div class="pull-right">
<button ng-click="signupCtrl.signupUser()">Register</button>
</div>
</div>
</li>
</ul>
</div>
Update- This is my Controller Code ##
someAppControllers.controller('signupCtrl', [
'$window',
'$scope',
'HttpReqHandlerService',
'$location',
'localStorageService'],
function($window, $scope, HttpReqHandlerService,
$location, localStorageService) {
$scope.signupUser=function signupUser() {
alert("hello");
}]);
The button is not calling signupUser function in my controller

Use $scope.signupUser instead of this.signupUser
Change you code as
someAppControllers.controller('signupCtrl', ['$window', '$scope',
function ($window, $scope) { // Here you have to define function an pass window and scope
$scope.signupUser = function signupUser() {
alert("hello");
};
}
]);
Additionally, You have syntax error.
HTML
Instead of
<input type="text" ng-model="signupCtrl.firstName">
<button ng-click="signupCtrl.signupUser()">Register</button>
Use
<input type="text" ng-model="firstName">
<button ng-click="signupUser()">Register</button>

You've written your markup as though you used the controller as syntax. To make it work just change your ng-controller="signupCtrl" to ng-controller="signupCtrl as signupCtrl";

Related

ng-submit is not working in Laravel PHP framework

everyone, I have another question related to Laravel/AngularJS.
In my mini-project, I have form which user can post question in the form, but when I click submit button, there are no requests (from inspect in Google Chrome). However, I have a Log in interface, the button is working very well. I use the same logic, same html structure. And I am wondering how can I fix this problem.
I have been debugging this for 2 hours, have been Googling for a long time. Please help me out!!
Below are the codes.
// Add question page
<script type="text/ng-template" id="question.add.tpl">
<div ng-controller="QuestionAddController" class="question-add container">
<div class="card">
<form name="question_add_form" ng-submit="Question.add()">
<div class="input-group">
<label>Title</label>
<input type="text"
name="title"
ng-minlength="5"
ng-maxlength="255"
ng-model="Question.new_question.title"
required>
</div>
<div class="input-group">
<label>Description</label>
<textarea type="text"
name="desc"
ng-model="Question.new_question.desc">
</textarea>
</div>
<div class="input-group">
<button ng-disabled="question_add_form.$invalid"
class="primary"
type="submit">Submit</button>
</div>
</form>
</div>
</div>
</script>
// Service and Controller
.service('QuestionService', [
'$http',
'$state',
function ($http, $state) {
var me = this;
me.new_question = {};
me.go_add_question = function () {
console.log(1);
$state.go('question.add');
};
me.add = function () {
if (!me.new_question.title)
return;
$http.post('/api/question/add', me.new_question)
.then(function (r) {
console.log('r', r);
// if (r.data.status) {
// console.log(r.data);
// me.new_question = {};
// $state.go('home');
// }
}, function (e) {
console.log('e', e);
})
}
}
])
.controller('QuestionAddController', [
'$scope',
'QuestionService',
function (QuestionService, $scope) {
$scope.Question = QuestionService;
}
])
in QuestionService.add(), there is no "return value" (console.log('r', r);) in my browser.
I make sure routes and url are working fine by directly typing the address in browser. Any suggestion will be highly appreciated!
Thanks in advance!!!
Edit:
Besides, the button Add Question is not working, too. I have to use ui-sref to make it redirect to the target url, will this be the reason why the submit button is not working (like I use ui-sref not the ng-submit to redirect)
// Add question
<div class="navbar clearfix">
<div class="container">
<div class="fl">
<div class="navbar-item brand">somethingHere</div>
<form ng-submit="Question.go_add_question()" id="quick_ask" ng-controller="QuestionAddController">
<div class="navbar-item">
<input ng-model="Question.new_question.title" type="text">
</div>
<div class="navbar-item">
<button ui-sref="question.add" type="submit">Add question</button> <!--ui-sref="question.add"-->
</div>
</form>
</div>
<blablabla something not important here!!!!>
Your injections in the controller is the wrong order. Should be
.controller('QuestionAddController', [
'$scope',
'QuestionService',
function ($scope, QuestionService) {
$scope.Question = QuestionService;
}
])
EDIT:
The ordering itself does not really matter, but the controller function argument ordering must match the ordering in the array. E.g.
Correct:
['QuestionService', 'Service2', '$scope', function(QuestionService, Service2, $scope) { ...
Incorrect:
['QuestionService', 'Service2', '$scope', function(QuestionService, scope, Service2) { ...
The reason to define the controller with array is so that the code can be minified

Execute a javascript function within a controller from a directive

I need to execute a javascript function that resides inside a controller. I need to call the function from within a directive.
The arguments I'm passing are fine. My method name in the controller is "GetAttachments".
When I'm debugging, and using scope, the method name GetAttachments doesn't appear.
Can someone please help me to be able to execute the named function?
Here is my directive. I need to know the proper syntax of the line: scope.GetAttachments(attrs.downloadType, attrs.downloadId). Note that my arguments are fine...
.directive('download', ['$modal', function ($modal)
{
return {
restrict: 'E',
transclude: false,
replace: true,
template: '<a style="padding-right: 5px; color:#fff !important;" class="pull-right" href="#" ng-click="opendownload()"><i class="fa fa-files-o fa-lg" style="padding-right: 5px"></i>Download</a>',
link: function (scope, elem, attrs, controller)
{
scope.opendownload = function ()
{
$modal.open({
templateUrl: root + 'AccountingModule/modal/attachment/download-modal.html',
size: 'md',
backdrop: true,
controller: 'downloadSPDocumentsController as downloadCtrl',
resolve: {
attributes: function () { return attrs; },
}
});
scope.GetAttachments(attrs.downloadType, attrs.downloadId)
}
}
}
}])
Here is my JS function inside the controller:
module.controller('downloadSPDocumentsController', ['$scope', '$http', '$modalInstance', '$location', '$window', 'attributes',
function ($scope, $http, $modalInstance, $location, $window, attributes)
{
var viewModel = this;
viewModel.attributes = attributes;
var DocumentDownloadarr;
viewModel.GetAttachments = function (CheckID, FileID)
{
Here is the HTML
<!--<p>For Testing Purpose: Download Type: {{downloadCtrl.attributes.downloadType}}</p>
<p>For Testing Purpose: ID: {{downloadCtrl.attributes.downloadId}}</p>-->
<div class="modal-header">
<h3 class="modal-title">File Download</h3>
</div>
<div class="modal-body" cg-busy="{promise:downloadCtrl.promise}">
<ul ng-init="downloadCtrl.Init()" class="list-unstyled">
<li ng-repeat="item in downloadCtrl.DocumentDownloadarr">
<div class="col-sm-12">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" ng-value="item.FileDescription" ng-readonly="true" />{{item.ExternalDocumentId}}
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-default" ng-click="downloadCtrl.DownLoadAttachment(item.ExternalDocumentId, item.FileDescription)">Download</button>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="modal-footer">
<div class=" btn-toolbar pull-right" role="toolbar">
<!--<div class="btn-group" role="group">
<button type="button" class="btn btn-default" ng-click="downloadCtrl.GetAttachments(downloadCtrl.attributes.downloadType, downloadCtrl.attributes.downloadId)">List Attachments</button>
</div>-->
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" ng-click="$close()">Close</button>
</div>
</div>
</div>
You need to expose your function GetAttachments in the controller via the scope.
Instead of
viewModel.GetAttachments = function (CheckID, FileID)
try this:
$scope.GetAttachments = function (CheckID, FileID)
However please note that this will work only if the directive and the controller is sharing the scope (which I think is the case on your code). However if you want to use isolated scope (for better modularity and re-usability) of the directive , then you will have to pass a reference of the method (in your controller) to the directive's scope using '&' binding.
Take a look at this fiddler here for a demo of isolated scope and calling function in controller from directives
You might want to consider raising an event in your directive using something like:
$rootScope.$broadcast('myEventHappened');
And then in your controller listen for it with something like:
$scope.$on('myEventHappened', function() {});
This approach will keep you from tightly coupling your directive to your controller.

I am trying to call text from input using angular js

I am trying to call text that has been added to an input using Angular JS, however in my console log I keep getting undefined.
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="serverip"/>
<button ng-click="save(serverip)">Save</button>
</div>
</div>
</li>
</ul>
</div>
js code
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.save = function(){
console.log($scope.serverip)
}
})
You don't need to pass the parameter to the save function (and your definition of save doesn't include it).
Change the button to:
<button ng-click="save()">Save</button>
Or either accept the parameter in the function declaration:
$scope.save = function(serverip){
console.log(serverip)
}
ng-repeat creates a new scope, inheriting from the scope above it. You are assigning serverip to this newly created scope. Thus, $scope in the favouritesController's context has no record of this. You should accept a parameter in your save function and log that (as you are passing this function the argument, anyways.)
Edit:
or, as an alternative... Expose a property that will be inherited by ng-repeat:
Controller:
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.ip = { serverip:'' };
$scope.save = function(){
console.log($scope.ip.serverip)
}
});
Template
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="ip.serverip"/>
<button ng-click="save()">Save</button>
</div>
</div>
</li>
</ul>
</div>

ng-repeat throwing invalid Expression

I'm a total angular noob and trying to create a simple test app where. I'd like to read out some userdata in a partial. The user data is in my event controller. I assign the event controller to a form in my new.html partial after navigating to #/new via a route controller.
The error I get when trying to loop through the users in my partial is "Error: ngRepeat:iexp Invalid Expression". I can't figure out how to ng-repeat through those users.
Any thoughts?
My index.html:
<div class="container" style="width: 500px; margin: 0 auto;">
<ul class="nav nav-pills" ng-controller="NavigationController as navigationCtrl">
<li ng-class="{active: navigationCtrl.isActive(1)}">
Home
</li>
<li ng-class="{active: navigationCtrl.isActive(2)}">
Nieuw
</li>
<li ng-class="{active: navigationCtrl.isActive(3)}">
Nog een
</li>
</ul>
<div ng-view></div>
</div>
My new.html partial
<form action="" ng-controller="EventController as event">
<div ng-repeat="users as user">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="user.name">
<br>
<label>Emailaddress</label>
<input type="email" class="form-control" name="email" ng-model="user.email">
<br>
<input class="btn btn-default" type="submit" ng-click="event.addEvent($event)" value="Klik">
</div>
</form>
And last: My angular code
(function () {
var app = angular.module('testApp', ['ngRoute']);
app.controller('NavigationController', ['$scope', '$route', function ($scope, $route) {
$scope.$route = $route;
this.activeTab = 1;
this.setActiveTab = function (tab) {
this.activeTab = tab;
};
this.isActive = function (tab) {
if ($route.current && $route.current.activeTab) {
return $route.current.activeTab === tab;
}
return false;
};
}]);
app.controller('EventController', ['$scope', '$controller', function ($scope, $controller) {
this.users = [
{name: 'aa'},
{name: 'bb'}
];
this.addEvent = function (e) {
e.preventDefault();
console.log(this);
};
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/new', {
templateUrl: 'partials/new.html',
controller: 'NavigationController',
activeTab: 2
}).
when('/another', {
templateUrl: 'partials/another.html',
controller: 'NavigationController',
activeTab: 3
}).
otherwise({
redirectTo: '/',
controller: 'NavigationController',
activeTab: 1
});
}]);
})();
I've tried changing this for $scope to no avail.
You write ng-repeat in wrong way in your new.html partial page
it should be like
new.html
<div ng-repeat="user in users">
Correct syntax for ng-repeat is
<element ng-repeat="item in [1,2,3]">
Also you can use things like track by $index if you have duplicated values in your collection like [1,1,1].
Ref. https://docs.angularjs.org/api/ng/directive/ngRepeat
There are few issues in your code. Please change all this references to $scope and then quickly fix below html code:
<div ng-repeat="user in users">
It should work but update me otherwise also.
Working demo for your reference (route codes excluded for demo purpose only)
thanks,
Ashok
you have not written ng-repeat in right way change it to:
<div ng-repeat="user in users">

How can I take a input value and put into a variable in angularJS?

How can I take a input value and put into a variable in angularJS?
this is the working testing version on my page but I did javascript and jquery together with angularJS to make it work but it is still giving me errors.
I know there must be a way to take the input value and put it inside of a var value through angularJS with out writting it manually how I'm doing it.
http://www.jaysg.com/poster
index.html
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Find That Poster</h1>
<div class="searchbox">
<button ng-click="start()" class="searchButton" id="btnSearch" value="Search">Search</button>
<p></p>
<input onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()">
</div>
</div>
</div>
</div>
</div>
<div class="content" ng-controller="StoreController as store">
<div class="container">
<div class="row">
<div >
<div class="col-md-3 posterImg" ng-repeat="product in store.products.results">
<span><img ng-src="http://image.tmdb.org/t/p/w300{{product.poster_path}}" class="img-responsive"></span>
<div >
<!-- <h2> {{product.original_title}}</h2>-->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
app.js // angular
(function() {
var app = angular.module('store', ['store-products']);//main app ng-app
app.controller('StoreController',[ '$http', function($http){
var store = this;
store.products = [ ];
$(document).ready(function() {
$( "input" ).keyup(function() {
var value = $( this ).val();
$('button').click(function() {
$http.get("http://api.themoviedb.org/3/search/movie?api_key=2f6ab7c6dc3db52d34703aae308640ef&query=" + value ).success(function(data){
store.products = data;
});
});
})
.keyup();
});
}]);
})();
You need the ng-model attribute.
Example:
<input onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click()" ng-model="search">
Then you can access the variable using $scope.search.
As I can see you are currently not injecting the $scope.
This is how to do it:
app.controller('StoreController', ['$scope', '$http', function($scope, $http){
See more in the docs.
It would also be advisable to rewrite your jquery event handlers to angular event handlers.
So instead of $('button').click(function() {, create a $scope.start() function that is bound to the click event of the search button.
to get the value of the variable use ng-model and to listen for the key down use ng-keydown
<div class="searchbox">
<button ng-click="search()" class="searchButton" id="btnSearch" value="Search">Search</button>
<p>
</p>
<input ng-keydown="press($event)" ng-model="searchField" >
</div>
and in your controller you call the functions you just bound to your dom elements
app.controller('StoreController', [
'$scope',
'$http',
function ($scope, $http) {
$scope.press = function (e) {
console.log(e.keyCode);
if (e.keyCode == 13) {
$scope.search();
}
};
$scope.search = function (e) {
$http.get("http://api.themoviedb.org/3/search/movie?api_key=2f6ab7c6dc3db52d34703aae308640ef&query=" + $scope.searchField )
.success(function(data){
$scope.products = data;
});
};
}
]);

Categories

Resources