I have a controller which works fine toggling hide and show on a div element at this stage I am trying to clean up so I started using a service.
Controller Snippet with toggle method inside
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = function (){
$scope.myVar = !$scope.myVar
//once toggled i.e form taken away success or failure message displayed for x time
$scope.successOrFailureAlert = true;
$timeout(function () {$scope.successOrFailureAlert = false}, 2000)
}
})
Service
app.service('Service', function($timeout){
var user = ""
var location = ""
this.toggle = function(var1,var2){
console.log(var1)
console.log(var2)
var1 = !var1
var2 = true;
$timeout(function () {var2 = false}, 2000)
}
})
Controller with service added
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = Service.toggle($scope.myVar, $scope.successOrFailureAlert)
//function (){
// $scope.myVar = !$scope.myVar
// once toggled i.e form taken away success or failure message displayed for x time
// $scope.successOrFailureAlert = true;
// $timeout(function () {$scope.successOrFailureAlert = false}, 2000)
//}
})
When I use the service instead of defining the method there. nothing happens the toggle dosen't fire. I wish I had more to add in regards to contextual information
HTML
<div ng-controller="addFormCtrl">
<span ng-show="successOrFailureAlert"> {{status}} </span>
<button ng-click="toggle()"> Add Employee </button>
<form ng-hide="myVar" ng-submit="submitAddEmployeeForm()">
<input type="text" ng-model="name">
<input type="text" ng-model="country">
<input type="submit" value="Submit" />
</form>
</div>
Call it inside a function, because your ng-click expects a function.
$scope.toggle = function(){
Service.toggle($scope.myVar, $scope.successOrFailureAlert);
}
Related
Hello i want to keep my radio button checked with previous value after refresh page i have also set variable value in controller but it is not working correct. here my html and angular code
<script>app.controller('commonController', ['$scope', 'httpMethodService', '$rootScope', 'growl', 'helperService', 'userService', '$auth','$routeParams',
function ($scope, httpMethodService, $rootScope, growl, helperService, userService, $auth,$routeParams,$routeProvider) {
$scope.$on('$routeChangeSuccess', function() {
if($routeParams.result == 'mlb'){
$scope.result == '1';
}else{
$scope.result == '2';
}
// $routeParams should be populated here
});
helperService.checkSubscribed();
$rootScope.isLoggedIn = false;
if (userService.checkExistKey('u_id')) {
$rootScope.isLoggedIn = true;
} else {
console.log("not-login");
$rootScope.isLoggedIn = false;
}
$scope.$watch('isLoggedIn', function () {
helperService.checkSubscribed();
});
$scope.authenticate = function (provider) {
$auth.authenticate(provider);
};
}]);</script>
here my HMTL
<div ng-init="submitResult(result);" class = "headerradio">
<lable>Choose a game- :</lable>
<input type="radio" ng-model='result'ng-click="submitResult(result);clearSearchParam();" ng-value='"1"' name="rdoResult">MLB
<input type="radio" ng-model='result' ng-click="submitResult(result);clearSearchParam();" ng-value='"2"' name="rdoResult">NFL
</div>
first controller will load so i am setting up value using $routParams and setting result value. but this code is not working.
I know the title is kind of ambiguous but here is the issue: I have 2 input fields in a form that look like this:
<form name="modifyApp" class="form-signin" ng-submit="modify(val)">
<input type="text" class="form-control" ng-model="val.name" id="appName">
<input type="number" class="form-control" ng-model="val.number" id="number" min="0" max="65535">
<button type="submit">Submit</button>
</form>
When I load the page I populate those two with some values from inside the controller:
angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
function setFields(appName, appNumber){
document.getElementById("appName").value = appName
document.getElementById("number").value = appNumber
}
$scope.modify= function(val){
console.log(val)
}
}])
The problem is when I press the Submit button. The values won't get registered unless I change them. For example, if I press the Submit button nothing gets printed, but if I change the number or the name, it gets printed.
In your controller you can simply initialize the val object like this:
angular.module('myApp', [])
.controller('modifyAppController', ['$scope', function($scope) {
$scope.val = {
name: '',
number: 0
};
function setFields(appName, appNumber) {
$scope.val.name = appName;
$scope.val.number = appNumber;
}
$scope.modify = function(val) {
console.log(val);
};
}]);
You need to rewrite your controller:
angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
$scope.val = {
name = 'My app name',
number = '1'
};
function setFields(appName, appNumber){
$scope.val.name = appName;
$scope.val.number = appNumber;
}
$scope.modify= function(){
console.log($scope.val);
}
}])
You don't need to directly modify the DOM values in Angular. All your $scope variables are available in your template.
why not just have the following as the first line in your form
<form name="modifyApp" class="form-signin" ng-submit="modify()">
and then your controller can look like this
$scope.val = {
name: '',
number:0//some default values
}
$scope.modify= function(){
console.log($scope.val)
}
I am trying to change the output value based on the user input, using angular. I can increment the value, however, when an input changes, the outputed value doesn't change
Here is my code:
<input type="text" ng-change="myFunc()" ng-model="myValue" />
<p>You have {{total}} points left.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myValue = 0;
$scope.total = 5;
$scope.myFunc = function() {
$scope.total -= $scope.myValue;
};
}]);
</script>
I want it that when the user, clicks, for instance, backspace, the total goes back to its initial value (which in this example, is 5)
any ideas?
I think it is simplier to do
<input type="text" ng-model="myValue" />
<p>You have {{total - myValue}} points left.</p>
<button type="button" ng-click="myFunc()">
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myValue = 0;
$scope.total = 5;
$scope.myFunc = function() {
$scope.total-=$scope.myValue;
};
}]);
</script>
Like this, user can see the value but apply it only with an explicit action
If you want to get back to the initial value, you can check the input length.
$scope.myFunc = function() {
if(!$scope.myValue.length){
$scope.total = 5;
}
$scope.total-=$scope.myValue;
}
http://jsfiddle.net/ugmv5od1/
I think in your change function you should have this. Add a scope.initial as the starting value rather than total, so you can go back to it when nothing is in the box.
$scope.initial=5;
$scope.myValue=0;
$scope.total = $scope.initial;
$scope.myFunc = function(){
$scope.total = $scope.initial - myValue;
}
Here is the relevant JSFiddle
https://jsfiddle.net/9Ltyru6a/3/
In the fiddle, I have set up a controller and a directive that I want to use to call a callback whenever a value is change. I know that Angular has an ng-change directive, but I want something more akin to the standard onchange event (that gets triggered once when the field is blurred).
Controller:
var Controllers;
(function (Controllers) {
var MyCtrl = (function () {
function MyCtrl($scope) {
$scope.vm = this;
}
MyCtrl.prototype.callback = function (newValue) {
alert(newValue);
};
return MyCtrl;
})();
Controllers.MyCtrl = MyCtrl;
})(Controllers || (Controllers = {}));
Directive:
var Directives;
(function (Directives) {
function OnChange() {
var directive = {};
directive.restrict = "A";
directive.scope = {
onchange: '&'
};
directive.link = function (scope, elm) {
scope.$watch('onChange', function (nVal) {
elm.val(nVal);
});
elm.bind('blur', function () {
var currentValue = elm.val();
scope.$apply(function () {
scope.onchange({ newValue: currentValue });
});
});
};
return directive;
}
Directives.OnChange = OnChange;
})(Directives || (Directives = {}));
HTML:
<body ng-app="app" style="overflow: hidden;">
<div ng-controller="MyCtrl">
<button ng-click="vm.callback('Works')">Test</button>
<input onchange="vm.callback(newValue)"></input>
</div>
</body>
The button works, so I can safely say (I think) that the controller is fine. However, whenever I change the value of the input field and unfocus, I get a "vm is undefined" error.
Thanks for the help!
First of all, use proper controllerAs notation, not $scope.vm = this;:
ng-controller="MyCtrl as vm"
Then don't mix custom directive with native onchange event handler - this is the reason why you get undefined error. Name your directive something like onChange and use on-change attribute instead.
Correct code would look like:
var app = angular.module("app", []);
var Directives;
(function (Directives) {
function OnChange() {
var directive = {};
directive.restrict = "A";
directive.scope = {
onChange: '&'
};
directive.link = function (scope, elm) {
elm.bind('blur', function () {
var currentValue = elm.val();
scope.$apply(function () {
scope.onChange({
newValue: currentValue
});
});
});
};
return directive;
}
Directives.onChange = OnChange;
})(Directives || (Directives = {}));
app.directive("onChange", Directives.onChange);
var Controllers;
(function (Controllers) {
var MyCtrl = (function () {
function MyCtrl($scope) {
}
MyCtrl.prototype.callback = function (newValue) {
alert(newValue);
};
return MyCtrl;
})();
Controllers.MyCtrl = MyCtrl;
})(Controllers || (Controllers = {}));
app.controller("MyCtrl", ["$scope", function ($scope) {
return new Controllers.MyCtrl($scope);
}]);
Demo: https://jsfiddle.net/9Ltyru6a/5/
If the intent of your code is to only update your controller value on blur, rather than update it on every keypress, angular has ngModelOptions for this use. For example:
<input type="text" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" />
you could even provide a debounce, or a button to clear the value....
<form name="userForm">
<input type="text" name="userName"
ng-model="user.name" ng-model-options="{ debounce: 1000 }" />
<button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
</form>
In these cases, if you were to supply an ng-change, it would only trigger on the blur event, or after the debounce.
You can also write directives that directly leverage the $validators or $asyncValidators from the ngModelController
here's an example from the Angular Developer Guide:
app.directive('username', function($q, $timeout) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var usernames = ['Jim', 'John', 'Jill', 'Jackie'];
ctrl.$asyncValidators.username = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty model valid
return $q.when();
}
var def = $q.defer();
$timeout(function() {
// Mock a delayed response
if (usernames.indexOf(modelValue) === -1) {
// The username is available
def.resolve();
} else {
def.reject();
}
}, 2000);
return def.promise;
};
}
};
});
and the HTML:
<div>
Username:
<input type="text" ng-model="name" name="name" username />{{name}}<br />
<span ng-show="form.name.$pending.username">Checking if this name is available...</span>
<span ng-show="form.name.$error.username">This username is already taken!</span>
</div>
You could of course add the ng-model-options to ensure that this triggers only once.
I have a button for updating data in ng-form. This button only appear when some form input is changed. I done this with $dirty.
When the Update is clicked, I update the data. But I want to hide this button when it clicked.
I have an ng-click method on button click.
I tried to hide it like this :-
$(this).hide();
The above solutions doesn't work & i also want some solution which is not jquery based.
HTML
<button class="btn-small" ng-click="updateData('contactinformation')" ng-show="contactinformationform.$dirty">Update</button>
CODE
$scope.updateData = function (category) {
switch (category) {
case 'basicinformation':
$scope.categorynewdata = $scope.data.basicinformation[0];
break;
case 'contactinformation':
$scope.categorynewdata = $scope.data.contactinformation[0]
break;
}
var query = {
category: category
};
Patients.updateData().save(query).$promise.then(function (data) {
alert('Data updated successfully..!');
});
}
You can use ng-hide in your button like this
Define scope variable (Like flag) so that you can decide when to hide/show button.
<button ng-click="btnClicked()" ng-hide="hideMe">Submit</button>
Controller
// Initialize hideMe variable
$scope.hideMe = false;
$scope.btnClicked = function() {
/* your code */
$scope.hideMe = true;
}
You can Try like this
Working Demo
html
<div ng-app='myApp' ng-controller="ArrayController">
<form>
<input type="text" ng-model="name" ng-change='flag=false' />: Name
<br>
<input type="text" ng-model="age" ng-change='flag=false' />: Age
<br>
<button class="btn-small" ng-click="updateData('contactinformation')" ng-hide='flag'>Update</button>
</form>
</div>
script
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.name = 'Manu';
$scope.age = '21';
$scope.flag = true;
$scope.updateData = function (value) {
$scope.flag = true;
}
});