Function is not calling in angular js when ng-change event occurs - javascript

Here is the code below i have studied several blogs but note found any way to resolve this problem.
HTML File:-
<ion-content ng-controller="IpScanner">
<div class="list">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="Barcode" ng-model="IpValue" ng-change="CartAction()" >
</label>
</div>
</div>
</ion-content>
JSFile
.controller('IpScanner', ['$scope', 'socket', function($scope, socket, $window, $timeout, $ionicPopup, $q) {
$scope.CartAction = function() {
window.alert('Onchange');
}
}])

I don't know if this was just a matter of bad cut and paste or freehand typing in, but your controller is not well-formed. You have an extra closing bracket (}) in there. Try this:
.controller('IpScanner', ['$scope', 'socket', '$window', '$timeout', '$ionicPopup', '$q', function($scope, socket, $window, $timeout, $ionicPopup, $q) {
$scope.CartAction = function()
{
window.alert('Onchange');
}
}]);

Related

ui-bootstrap modal won't close or dismiss

New to ui-bootstrap and I've gotten the modal to appear, but can't get it to dismiss with a button press. I've tried a many combinations but nothing seems to work (or it makes the modal not appear at all).
The modal is in a separate file as:
<div ng-controller = 'entryCtrl' class="modal" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body">
<div class="modal-inner-content">
</div>
<div class="modal-footer" id="modal-footer">
<button type="button" class="btn btn-success" ng-click="cancel()"><i class="glyphicon glyphicon-backward"></i> Back</button>
<button type="button" class="btn btn-danger" ng-click="ok()"><i class="glyphicon glyphicon-forward"></i> Continue</button>
</div>
</div>
</div>
</div>
</div>
It's called in a different html file with the same controller (I tried having them as different controllers, but then variables wouldn't appear to inject at all, i.e. the modal instance would be undefined).
In the controller, I can get the thing to open as:
xControllers.controller('entryCtrl', [
'$scope', '$window', '$modal', '$log',
'SharedProperties',
function ($scope, $window, $modal, $log,
SharedProperties) {
$scope.open = function (size) {
$scope.modal = $modal({
templateUrl: './views/modals/possible_slurs.html',
controllerAs: ['$window', '$log', '$modalInstance', function ($window, $log, $modalInstance) {
this.ok = function () {
$modalInstance.close();
};
this.cancel = function () {
$modalInstance.dismiss('cancel');
$window.history.back();
};
}],
scope: $scope
});
};
}]);
For some reason the $modal.open() doesn't work, and template, and controller parameters don't either (it only accepts templateUrl and controllerAs).
I attempted to have controllerAs set as a different controller, but then that separate controller wouldn't recognize the modal instance (it came up as undefined).
I have my dependencies set as:
var x = angular.module('x-app', [
'xControllers',
'ngAnimate',
'ngRoute',
'ngResource',
'mgcrea.ngStrap',
'angularUtils.directives.dirPagination',
'ui.bootstrap'
]);
And their versions:
"dependencies": {
"socket.io": "^2.2.0",
"angular": "^1.7.8",
"angular-animate": "^1.7.8",
"angular-motion": "^0.4.4",
"angular-resource": "^1.7.8",
"angular-strap": "^2.3.12",
"bootstrap": "^4.3.1",
"jquery": "^3.4.1",
"angular-bootstrap": "^2.5.0"
}
Thank you so much and please let me know if more information is needed to help with this!
This is the most convoluted thing I've ever come across. After several hours and days going back and forth in documentation, I've found the answer: which is, of course, that there were many, many problems going on and the fact that anything was showing up at all was a total fluke.
I'll just post what I got working, but suffice it to say: the Angular version is very important here.
The new working modal (notice that there is no controller specified here nor any of those wrapping divs):
<div class="modal-header"></div>
<div class="modal-body">
<div class="modal-inner-content">
</div>
<div class="modal-footer" id="modal-footer">
<button type="button" class="btn btn-success" ng-click="cancel()"><i class="glyphicon glyphicon-backward"></i> Back</button>
<button type="button" class="btn btn-danger" ng-click="ok()"><i class="glyphicon glyphicon-forward"></i> Continue</button>
</div>
</div>
The new working controller which opens the modal (note the switch to $uibModal):
xControllers.controller('entryCtrl', [
'$scope', '$window', '$uibModal', '$log',
'SharedProperties',
function ($scope, $window, $uibModal, $log,
SharedProperties) {
$scope.open = function (size) {
$uibModal.open({
templateUrl: './views/modals/modal.html',
controller: 'modalInstanceCtrl',
scope: $scope
});
};
}]);
And the new modal controller called within that controller:
xControllers.controller('modalInstanceCtrl', [
'$scope', '$window', '$uibModalInstance',
function ($scope, $window, $uibModalInstance) {
$scope.ok = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.close();
$window.history.back();
};
}]);
And that seemed to do the trick. A large thanks to whoever created this Plunker (http://embed.plnkr.co/4VcNom/) because the official documentation was essentially the opposite of useful in this regard (https://angular-ui.github.io/bootstrap/; it only handles the case where a modal's HTML is loaded in the same HTML doc as the main HTML, not for separate files).
Anywho, hope this helps others.

How to show one div on click and hide others on click using ui-route?

my js:
var app = angular.module("dashboardApp", ["ngMaterial", "ngAnimate", "ngSanitize", "ui.bootstrap", "ngAria", "ui.router", "datatables", "gridshore.c3js.chart"]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider){
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/systems');
$stateProvider
.state('systems',{
url:"/systems",
templateUrl: 'pages/systems.html'
})
.state('summary', {
url:"/summary",
controller:"maxeCtrl",
templateUrl: 'pages/summary.html'
});
});
app.run(function($rootScope, $location, $anchorScroll, $stateParams, $timeout) {
$rootScope.$on('$stateChangeSuccess', function(newRoute, oldRoute) {
$timeout(function() {
$location.hash($stateParams.scrollTo);
$anchorScroll();
}, 100);
});
});
Here i am trying to inject $anchorScroll and it will scroll you to any element with the id found in $location.hash() ----> which in case here is incident.
page1:
<div class="system_row2">
<div class="col-sm-3">Today Incident's:</div>
<div class="col-sm-9 ">
<div class="col-sm-12">
<a ui-sref="summary({scrollTo:'incident'})">
</a>
</div>
Page2: i am using accordion here and providing id="incident" which will scroll to this element.
<div id="abc">
this is div 1
</div>
<div uib-accordion-group id="incident" class="panel-default">
<uib-accordion-heading>
<div class="accordion_heading">Incidents</div>
</uib-accordion-heading>
<uib-accordion-body> </uib-accordion-body>
<table>
</table>
</div>
Mycontroller:
app.controller("maxeCtrl", ["$scope", "MAXeService", "DTOptionsBuilder", "$timeout", function($scope, MAXeService, DTOptionsBuilder, $timeout) {
console.log("Angular: MAXeCtrl in action")
$scope.oneAtATime = true;
$scope.status = {
isFirstOpen: true,
isSecondOpen: true
};
I want div id="incident" to be displayed when user clicks on "summary({scrollTo:'incident'})" and the other div with id="abc" should hide.
Appreciate any kind of help in advance.
I think you are looking for named views. Check here
https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views
Sample from above link
<!-- index.html -->
<body>
<div ui-view="filters"></div>
<div ui-view="tabledata"></div>
<div ui-view="graph"></div>
</body>
Routing
$stateProvider
.state('report',{
views: {
'filters': {
templateUrl: 'report-filters.html',
controller: function($scope){ ... controller stuff just for filters view ... }
},
'tabledata': {
templateUrl: 'report-table.html',
controller: function($scope){ ... controller stuff just for tabledata view ... }
},
'graph': {
templateUrl: 'report-graph.html',
controller: function($scope){ ... controller stuff just for graph view ... }
}
}
})
for ui-router >=1.0 check here https://ui-router.github.io/guide/views#multiple-named-uiviews

Angular giving a weird templateURL

I am trying to navigate to another page by using the selected objectID.
Angular Routing,
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
});
Angular Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
// This To get request all the books: it works fine
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
// This to get request a book with specific id it works fine
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
And then I have this html page which work also fine accept the button in the page, this button supposed to give me a clean templateUrl to navigate to another html page but it give me weird URL:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary" href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
And once I press the button I'm supposed to get a clean url such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
but instead I get this url!
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Seems like you have hashprefix !, then your URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Its because your url is getting converted into codes. %2f means a /.
You need to have this configuration to avoid this behavior of angular
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
You have Prefix in url which is converting into character i.e url encoding.
So you need to fix $locationProvider's hashPrefix property by replacing its value with empty/blank string
$locationProvider.hashPrefix('');

ng-click and ng-submit doesn't work

i have a angular application with phonegap where i have a login form and login controller.
The problem is that the ng-submit doesn't work. Normaly the submit call the fonction formConnexion() but nothing happens. So, i tried with just a alert, but it's the same result...
After i tried with a ng-click and same result. Then, i wanted try to call a sample variable in the scope in the template ($scope.test) and it doesn't display. And the console.log('salut!!') doesn't dispaly when i am on the login page.
Which made me think that my controller it doesn't associate to the template.
But i have the ng-controller in my div with the good name controller.
Then, i thought that angular it's was worse installing but no because the other directives work (ng-if, ng-src, ...)
So, if you have a idea to solve this problem, I do not mind :)
here the code for the template :
login.html
<div class="row jumbotron" style="margin:10px" ng-controller="LoginCtrl">
<div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2 col-xs-8 col-xs-offset-2">
<h1>{{ test }}</h1>
<form class="form-horizontal" ng-submit="alert('alert')">
<div class="form-group">
<label for="login" class="control-label">Login</label>
<input type="text" name="login" class="form-control" ng-model="formData.login">
</div>
<div class="form-group">
<label for="password" class="control-label">Password</label>
<input type="password" name="password" class="form-control" ng-model="formData.password">
</div>
<button type="submit" class="btn btn-md btn-success">Connexion</button>
</form>
click
<img ng-src="images/accueil.png" class="accueil img-responsive">
</div>
</div>
and here the controller :
login.js
'use strict';
appStat.controller('LoginCtrl', function ($scope, $rootScope, $http, $location) {
console.log("salut!!");
$scope.formData = {};
$scope.test = "test";
$scope.toto = function() { alert('alert'); };
/**
* Connect l'user
*/
$scope.formConnexion = function () {...}
});
and here my app.js :
app.js
'use strict';
var appStat = angular.module('posStatsPhoneGap', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ngResource',
'ui.bootstrap',
'ngMessages',
'ngAnimate',
'ngAria',
'ngTouch',
'picardy.fontawesome'
])
.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|tel):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|tel):/);
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/stat', {
templateUrl: 'views/stat.html',
controller: 'StatCtrl'
})
.otherwise({
redirectTo: '/'
});
}
]);
Thank you in advance !
Following from my comment Try something like this:
Create a Controller file & a controller within it Create a angular
module within the controller file
Create a controller.js file then create a angular module see code below:
//Within your controller.js file
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http){
$scope.Data = "Alert Alert";
// Create a function within the scope of the module
$scope.myFunc = function(){
alert($scope.Data)
};
});
Then within your HTML file call the function on-Click see code below:
Note: Don't forget to add the controller you created into your HTML code. I usually add it in the body tag
<body ng-controller="myController">
<button ng-click="myFunc()">Make Request Button</button>
</body>
See a live example here:
http://plnkr.co/edit/sQ0z7TlyWv5fM5XyfujK?p=preview
Also a note: ng-click is mostly used for any click events you are trying to perform within your angular app but ng-submit is mostly used when working with a HTML form submission.
Use ng-submit in you form as:
<form ng-submit="submit()">
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function () {
if ($scope.text) {
$scope.list.push($scope.text);
$scope.text = '';
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit()">Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre>
</form>
<button ng-click="submit()">Submit 2</button>
</div>
</div>
I found the error. It was caused by having 2 controllers with the name 'LoginCtrl'. It was a stupid copy/paste error.
I have created one working code for the above question for 4 different type of HTML element, for complete code please follow the below URL -
http://plnkr.co/edit/Tm2Rtbt3xsv4pKzcPQCw?p=preview
<body ng-controller="ExampleController">
<button ng-click="setButton()">set button</button>
<div content="snippetContentFirst"></div>
<div content="snippetContentSecond"></div>
<div content="snippetContentThird"></div>
<div>
<ul content="snippetContentFour"></ul>
</div>
</body>

How to make Angular Routing with title instead of id?

I am building a blog with angular and am currently working on the routes. I have the routes working with routeParams but angular gives it a random number and the url ends like http://localhost/kensproblems/#/posts/2
I want it to either automatically grab the title and use it as the parameter on the URL or use the property called id on the json file such as http://localhost/kensproblems/#/posts/title-of-post
Is this possible with $routeParams?
app.js
angular.module('app', [
'ngRoute',
'app.controllers',
'ui.router',
'ngSanitize'
])
.config(['$routeProvider', '$urlRouterProvider', function($routeProvider, $urlRouterProvider){
$routeProvider
.when('/posts', {
templateUrl: 'views/posts.html',
controller: 'PostListController'
})
.when('/posts/:id', {
templateUrl: 'views/singlepost.html',
controller: 'PostDetailController'
})
.otherwise({
redirectTo: '/'
});
}]);
controllers.js
angular.module('app.controllers', ['app.directives'])
/* Controls the Blog */
.controller('PostListController', ['$scope', '$http', function($scope, $http){
$http.get('data/posts.json').success(function(response){
$scope.posts = response;
});
}])
.controller('PostDetailController', ['$scope', '$http', '$routeParams', '$sce', function($scope, $http, $routeParams, $sce){
$http.get('data/posts.json').success(function(response){
$scope.post = response[$routeParams.id];
console.log($routeParams.id);
console.log($scope.post.id);
});
}])
posts.html
<div class="container" id="postList">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div ng-repeat="post in posts | orderBy:post.date" class="post">
<h2 class="blog-title">{{post.title}}</h2>
<span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>
<div class="row top10">
<div class="col-md-8">
<div class="post-content">{{post.headline}}</div>
<a class="read-more" href="#/posts/{{posts.indexOf(post)}}">Read more</a>
</div>
</div>
</div>
</div>
</div>
</div>
singlepost.html
<div class="container" id="singlePost">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h1>{{post.id}}</h1>
<h1>{{post.title}}</h1>
<span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>
<h3>{{post.headline}}</h3>
<div class="postContent" ng-bind-html="post.content"></div>
</div>
</div>
</div>
You will need to change two main things, first how the URLs are generated, and second how the post is recovered.
Generate URL from title
Not any title will be valid as URL, so you need to use slugs.
In the view:
<a class="read-more" href="#/posts/{{getSlug(post.title)}}">Read more</a>
In the controller:
$scope.getSlug = function(text){
return text.replace(/\W+/g, '-');
};
Search post from slug
Currently, you are just fetching the post from the array as an index, which is conceptually wrong (you will notice this after remove one post). Instead, make a search through the array. This will be really simple if you use lodash.
Something like this would work:
$scope.post = _.find(response, function(post) {
return post.title.replace(/\W+/g, '-') === $routeParams.id;
});
Stack Overflow won't let me comment yet so I'll post here. I looks like your passing the index of the post in the array instead of one of the properties. Look at changing:
href="#/posts/{{posts.indexOf(post)}}"
To something like:
ng-href="#/posts/{{post.title}}"

Categories