Setting Page Update Profile Name in AngularJS - javascript

Hi Guys I need to change the existing profile name in settings page.
1. First Name must be displayed in Username: {{name}}
2. I have given button to show dialog box to change name, when clicked save the name must be changed and displayed in the Username:{{name}} That is all i needed.. I need code like below, This code is just a example..
var app = angular.module('AngularApp', ['ngMaterial']);
app.controller('SettingCtrl', ['$scope', '$mdDialog',
function($scope, $mdDialog) {
$scope.name = "test";
$scope.ChangeName = function(ev) {
$mdDialog.show({
controller: SetDialogController,
template: '<md-dialog aria-label="Add insert" md-theme="dialogtheme"><md-content>' +
'<form name="ChangeName"><div layout layout-sm="column"><md-input-container flex>' +
'<label>Client Name</label><input ng-model="newname" placeholder="New Name">' +
'</md-input-container><div></form> </md-content>' +
'<div class="md-dialog-actions" layout="row"> <span flex></span>' +
'<md-button ng-click="cancel()"> Cancel </md-button>' +
'<md-button ng-click="saveClient()" class="md-warn"> Save </md-button>' +
'</div></md-dialog>',
targetEvent: ev,
clickOutsideToClose: true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
}
]);
function SetDialogController($scope, $mdDialog) {
$scope.saveClient = function() {}
$scope.cancel = function() {
$mdDialog.cancel();
};
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>ViewSalesVisit</title>
<!-- <link href="css/style.css" rel="stylesheet"> -->
<link href="js/angular-material.min.css" rel="stylesheet">
<!-- cordova script (this will be a 404 during development) -->
<!-- <script src="cordova.js"></script> -->
<script src="js/angular.min.js"></script>
<script src="js/angular-material.min.js"></script>
<script src="js/angular-aria.min.js"></script>
<script src="js/angular-animate.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="AngularApp" ng-controller="SettingCtrl">
<div>
<md-content md-scroll-y>
<md-toolbar class="md-toolbar-tools" layout-align="center">
<h3>Settings</h3>
</md-toolbar>
<div>
<h1>Username: {{name}}</h1>
<md-button class="md-primary md-raised" ng-click="ChangeName($event)" flex="100" flex-gt-md="auto">
Change Username
</md-button>
</div>
</md-content>
</div>
</body>
</html>
Thank you in advance guys..

Related

angularjs + bootstrap, btn in template function

I am learning angularjs and bootstrap.
It is simple, but I dont know, what I am doing wrong.
The point is to reload the page with a button, but I was not able to get inside the function, which has to reload the page.
This is my component.js
myApp.component('refreshComponent', {
template:"<button class='btn btn-lg btn-info' ng-click='refresh()' >Refresh </button>",
controller: function RefreshController($scope, $element, $attrs) {
var vm = this;
vm.refresh = function(){
console.log("How to get here?")
location.reload();
}
}
});
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>
<div ng-app="myApp" class="container bg-primary img-rounded">
<h1>
<div class="row">
<div class="col-xs-6 text-right">
<date-component></date-component>
</div>
</div>
<div class="row">
<div class="col-xs-6 text-right">
<greetings-component></greetings-component>
</div>
</div>
<div class="row">
<div class="col-xs-6 text-right ">
<refresh-component></refresh-component>
</div>
</div>
</h1>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script src="date.component.js"></script>
<script src="greetings.component.js"></script>
<script src="refresh.component.js"></script>
</body>
</html>
BTW those other componnent are working
var myApp = angular.module('myApp', []);
myApp is initialized in date.component.js
Be sure you added controllerAs: 'vm', to your component and ng-click='refresh() to ng-click='vm.refresh()
So your component should look like:
myApp.component('refreshComponent', {
template:"<button class='btn btn-lg btn-info' ng-click='vm.refresh()' >Refresh </button>",
controllerAs: 'vm',
controller: function RefreshController($scope, $element, $attrs) {
var vm = this;
vm.refresh = function(){
console.log("How to get here?")
location.reload();
}
}
});
Tip 1:
if you use vm, you don't need $scope at all. A.e.:
function RefreshController($element, $attrs)
Tip 2:
If you go to obfuscate your code, worth to use $inject to avoid unexpected behavior:
myApp.component('refreshComponent', {
template:"<button class='btn btn-lg btn-info' ng-click='vm.refresh()' >Refresh </button>",
controllerAs: 'vm',
controller: RefreshController
});
function RefreshController($element, $attrs) {
var vm = this;
vm.refresh = function(){
console.log("How to get here?")
location.reload();
}
}
RefreshController.$inject = ['$element', '$attrs'];

update function parameters on some other function

here i am stuck in my app with comments. i am making an app facebook like. where comment button take me to specific post is viewed on ionicModal. and i can comment on that post. My problem is i can comment on that post i cannot update it instantly where i have to close my modal and reopen to view updated data.
Here's my code
feed is ng-repeat value
<div ng-click="commentModalOpen(feed)">
the modal code is
$ionicModal.fromTemplateUrl('templates/comment.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.commentModal = modal;
});
$scope.commentModalOpen = function(feed) {
$scope.commentModal.show();
$scope.feed = feed;
};
where $scope.feed show me my post on ionicModal and update comment on modal
<textarea ng-model="obj.postcomment" id="postcomment" placeholder="Your Comment" autofocus="true"></textarea>
<div ng-click='btn_add(feed.PostId,obj);' >Post Comment</div>
the btn_add add my comments although want to show my updated comment on the ionicModal it self which im not able to
suggest some solution
Thanks in advance
Hopefully, the following example will clear things up. I recommend testing it out on play.ionic.io
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="https://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet">
<script src="https://code.ionicframework.com/1.0.0/js/ionic.bundle.js"></script>
</head>
<body ng-app="app">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Awesome App</h1>
</ion-header-bar>
<ion-content class="padding" ng-controller="MainCtr">
<button class="button button-assertive" ng-click="openModal()">I'm a button</button>
</ion-content>
</ion-pane>
<script id="my-modal.html" type="text/ng-template">
<ion-modal-view>
<ion-header-bar>
<h1 class="title">My Modal title</h1>
</ion-header-bar>
<ion-content>
<div ng-repeat="obj in feed">
<div>{{obj.text}}</div>
<div>
<textarea ng-model="obj.postcomment" id="postcomment" placeholder="Your Comment" autofocus="true"></textarea>
<button ng-click="obj.text = obj.postcomment">post</button>
</div>
</div>
</ion-content>
</ion-modal-view>
</script>
</body>
</html>
js
angular.module('app', ['ionic']).controller('MainCtr', function($scope, $ionicModal) {
$scope.feed = [
{text:'fb is dumb ~la', postcomment:''},
{text:'no it\'s not lol', postcomment:''}];
$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function() {
$scope.modal.show();
};
});

Angular Material app - delayed changes

I was developing a simple stopwatch app using AngularJS + Angular Material + Electron, and somehow the data changes/watches were being delayed, until another UI interaction takes place (?) This had never happened before when I was using Bootstrap, and I can confirm it is not Electron that is the issue.
As I'm starting out today with these, I've made use of latest versions of AngularJS, Angular Material and Electron, all pulled with Bower.
EDIT: Here's the pen: http://codepen.io/anon/pen/jWgzev
Here's where the app starts:
Upon pressing the play button, the timer starts counting down to zero, and the play button gets replaced:
And when the timer hits zero, the button should have been replaced by an orange stop button, and yet it does not happen:
And when you hover your mouse over one of the two buttons on screen, the gray button magically transforms to orange:
I apologize in advance if I'm posting blocks of code, I just don't know where the problem is.
HTML:
<!doctype html>
<html class="no-js" lang="" ng-app="breaktime-stopwatch">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="styles/normalize.min.css">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="styles/font-awesome.min.css">
<link href="./bower_components/angular-material/angular-material.css" rel="stylesheet" />
<link rel="stylesheet" href="styles/app.css">
<!--<script src="scripts/vendor/modernizr-2.8.3.min.js"></script>-->
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
</head>
<body ng-controller="AppController as vm" layout="column">
<md-toolbar layout="row">
<div class="md-toolbar-tools">
<span>
<h1 class="md-title">Breaktime Stopwatch</h1>
</span>
<!-- fill up the space between left and right area -->
<span flex></span>
<md-button href="" class="md-icon-button">
<md-icon md-font-icon='fa fa-question-circle fa-2x'></md-icon>
<md-tooltip md-direction="left">
About and Help
</md-tooltip>
</md-button>
</div>
</md-toolbar>
<md-content layout="column" layout-padding>
<div flex layout="row" layout-align="center center">
<!--<md-progress-circular md-mode="indeterminate" md-diameter="50"></md-progress-circular>-->
<!--<md-progress-circular md-mode="determinate" ng-value="meter" md-diameter="50"></md-progress-circular>-->
<timer class="clock md-display-4" autostart="false" interval="1000" countdown="break_duration" finish-callback="stopTimer()">{{minutes}}:{{seconds}}</timer>
</div>
<div layout="row" layout-align="center center">
<span ng-if="playButton">
<md-button class="md-fab md-primary" aria-label="Play" ng-click="startTimer()">
<md-icon md-font-icon='fa fa-play fa-2x'></md-icon>
<md-tooltip md-direction="top">
Start
</md-tooltip>
</md-button>
</span>
<span ng-if="stopEarlyButton">
<md-button class="md-fab md-accent" aria-label="Stop Earlier" ng-click="stopEarlyTimer()">
<md-icon md-font-icon='fa fa-stop fa-2x'></md-icon>
<md-tooltip md-direction="top">
Stop
</md-tooltip>
</md-button>
</span>
<span ng-if="stopButton">
<md-button class="md-fab md-warn" aria-label="Stop" ng-click="stopTimer()">
<md-icon md-font-icon='fa fa-exclamation fa-2x'></md-icon>
<md-tooltip md-direction="top">
Stop
</md-tooltip>
</md-button>
</span>
</div>
</md-content>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<!--pre-dependencies-->
<script src="scripts/plugins.js"></script>
<!--dependencies-->
<script src="./bower_components/jquery/dist/jquery.min.js" type="text/javascript" ></script>
<script src="./bower_components/angular/angular.js" type="text/javascript" ></script>
<script src="./bower_components/angular-animate/angular-animate.js" type="text/javascript" ></script>
<script src="./bower_components/angular-aria/angular-aria.js" type="text/javascript" ></script>
<script src="./bower_components/angular-material/angular-material.js" type="text/javascript" ></script>
<script src="./bower_components/momentjs/min/moment.min.js" type="text/javascript" ></script>
<!--<script src="./bower_components/momentjs/min/locales.min.js" type="text/javascript" ></script>-->
<script src="./bower_components/humanize-duration/humanize-duration.js" type="text/javascript" ></script>
<script src="./bower_components/angular-timer/dist/angular-timer.min.js" type="text/javascript" ></script>
<!--application config-->
<script src="scripts/app.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<!--<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>-->
</body>
</html>
JS:
(function () {
'use strict';
var btsw = angular.module('breaktime-stopwatch', [
'ngMaterial',
'timer'
]);
btsw.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('indigo')
.accentPalette('grey');
});
btsw.controller('AppController', function AppController($scope, $mdDialog){
$scope.timerRunning = false;
$scope.playButton = true;
$scope.stopEarlyButton = false;
$scope.stopButton = false;
$scope.break_duration = 10;
$scope.break_var = angular.copy($scope.break_duration);
// $scope.meter = 0;
$scope.startTimer = function (){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
$scope.playButton = false;
$scope.stopEarlyButton = true;
};
$scope.stopEarlyTimer = function (){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
$scope.playButton = true;
$scope.stopEarlyButton = false;
};
$scope.stopTimer = function (){
$scope.stopEarlyButton = false;
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
$scope.playButton = false;
$scope.stopEarlyButton = false;
$scope.stopButton = true;
};
$scope.test = function(){
console.log($scope.break_duration);
console.log($scope.break_var);
// console.log($scope.meter);
}
$scope.$on('timer-tick', function (event, data) {
$scope.break_var = data.millis/1000;
// if($scope.meter < Math.round(100-(($scope.break_var/$scope.break_duration)*100)))
// {$scope.meter = Math.round(100-(($scope.break_var/$scope.break_duration)*100));}
// console.log($scope.meter);
});
});
})();
Any kind of help that will point me to the right direction will be greatly appreciated!
Without digging into the timer code too much, I'm guessing that the finish-callback functionality that it provides may be running at the end of the digest loop, or entirely outside of Angular's digest cycle (which is a bit odd since it's an Angular module).
If this is the case, simply adding $scope.$digest(); to the end of your $scope.stopTimer() function should do the trick.
Here is an updated Codepen which works as expected: http://codepen.io/topherfangio/pen/bEXXNj
EDIT: As a side-note: it changes in your Codepen after hovering the button because the tooltip is triggering a digest cycle.

Updating a variable inside Service

Right I've got a really dumb one for you, and I've been looking at this code all day with no result.
I have a simple textbox which goes through a controller and updates a variable inside a service (The service will eventually fetch/update data from somewhere else).
At the moment, I am able to retrieve the variable value all the way to the view and it works, but the textbox is unable to update the variable inside the service in order to then display the new variable value in the view again....
I really appreciate any help and hope I have made sense!!!
// APP/APP.JS
(function(){
var app = angular.module('appMod', ['ngRoute', 'ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'introController',
templateUrl: 'app/partials/intro.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('nameController', function($scope, dataService) {
var nameValue;
this.name = dataService.getName();
this.submitName = function(nameVal) {
nameValue = this.nameCtrl.nameVal;
dataService.setName(nameValue);
};
});
app.controller('introController', function($scope, dataService) {
this.name = dataService.getName();
});
app.service('dataService', function () {
var name = "f";
this.getName = function() {
return name;
};
this.setName = function(nameVal) {
name = nameVal;
};
});
})();
<!-- INDEX.HTML -->
<!DOCTYPE html>
<html ng-app="appMod">
<head>
<link rel="stylesheet" type="text/css" href="content/css/normalize.css">
<link rel="stylesheet" type="text/css" href="content/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/style.css">
<link rel="stylesheet" type="text/css" href="content/css/animation.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.min.js"></script>
<script type="text/javascript" src="scripts/angular-timer.min.js"></script>
<script type="text/javascript" src="scripts/angular-animate.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body>
<div class="container">
<div class="row" ng-controller="nameController as nameCtrl">
<img src="content/images/sitelogo.png" class="logo">
<h2 class="welcomeMessage fade">Welcome <span class="fade" ng-show="!nameCtrl.name == ''">{{nameCtrl.name}}</span><span class="inline fade" ng-hide="nameCtrl.name !== ''">Friend</span> <small>(We like to get personal!)</small></h2>
<div class="namebox fade">
<h2>Welcome <small class="fade">Please type your name</small></h2>
<form class="fade">
<div class="form-group">
<input type="text" class="form-control" ng-model="nameCtrl.nameVal" autofocus>
</div>
<button type="submit" style="width:100%;" class="btn btn-default fade" ng-click="nameCtrl.submitName()" >Submit</button>
</form>
</div>
</div>
</div>
<div ng-view></div>
</body>
</html>
You need to be binding to name and not nameVal on your input
Then just pass that in your setName call, i don't think the rest of the code is needed in there, you can get rid of the nameValue var too.
this.submitName = function() {
dataService.setName(this.name);
};
The nameValue var is local to the controller and not available on the $scope to bind to your view, so even though you were changing it, the view didn't know about it as it couldn't see that var.

ng-show and $scope.$apply issue

On the HTML I have an overlay div to show a loading progress which uses the directive ng-show="showLoading". On the template ng-click I call the controller searchRequest method. This method updates showLoading to true just before making the http request.
If I do it this way the loading doesn't show, if I use the $scope.$apply to update the variable then I got the $apply already in progress error message. What is going on? How should I do this?
This is the index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="js/angular-route.js" ></script>
<!-- your app's js -->
<script src="js/searchController.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="myApp" ng-init="showLoading = false">
<div id="overlay" ng-show="showLoading">
<img id="loading" src="img/ajax-spinner.gif" />
</div>
<div ng-view></div>
</body>
</html>
The template:
<div ng-controller="searchController as searchController">
<ion-header-bar class="bar-stable">
<h1 class="title">Movie Searcher</h1>
</ion-header-bar>
<ion-content>
<label class="item item-input">
<span class="input-label">Title</span>
<input style="border-style: solid;border-width: 1px;" type="text" ng-model="searchController.searchString" required>
</label>
<button class="btn" ng-click="searchController.search()">Search</button>
{{response}}
</ion-content>
</div>
And the controller:
this.searchRequest = function(url) {
$scope.showLoading = true;
$http.get(url).success(function(data) {
$scope.showLoading = false;
//console.log("Success: " + JSON.stringify(data));
$scope.response = JSON.stringify(data);
for (i=0; i<data.length; i++) {
var movie = data[i];
//console.log("Movie: " + movie);
var genres = '';
for (j=0; j<movie.genres.length; j++) {
genres += movie.genres[j];
if (j < movie.genres.length - 1) {
genres += ', ';
}
}
console.log("Title: " + movie.title);
console.log("Plot: " + movie.simplePlot);
console.log("genres: " + genres);
}
})
.error(function(data, status, headers, config) {
$scope.showLoading = false;
$scope.response = "Error: " + status;
})};
Your Overlay div does not have the data context of the right controller.
When you specify the ng-controller directive, you are telling angular to use that specific controller as its current scope.
<div ng-controller="searchController as searchController">
Whereas for your body section here, you did not specify the right controller. So, angular doesn't know where showloading property is coming from.
<body ng-app="myApp" ng-init="showLoading = false">
<div id="overlay" ng-show="showLoading">
<img id="loading" src="img/ajax-spinner.gif" />
</div>
<div ng-view></div>
</body>
Either move the overlay div into the div which has the controller as context or try using $rootScope instead.
Probably the easiest way to force a digest cycle without having to worry about the phase is to wrap the var change call inside a $timeout function:
$timeout(function() {
$scope.showLoading = true;
}, 0);
$http.get(url).success(function(data) {
...
Of course, don't forget to inject $timeout as a dependency in your controller.

Categories

Resources