Angularjs getting the button value - angularjs

I need to get the button id value using angularjs.I have written the code but i am getting the value as "undefined".So please suggest me the code which i need to use.
My code is:
<button type="button" class="btn btn-primary ole" data-toggle="tooltip" id="buttonvalue" name="rdoResult" value="SUN" ng-click="addvalue()" ng-model="testDate23" data-placement="left" data-original-title="this is a left tooltip">
SUN
</button>
<button type="button" ng-value="2" class="btn btn-primary ole two" data-toggle="tooltip" ng-click="addvalue()"
ng-model="testDate23" value="MON" id="buttonvalue" data-placement="top" data-original-title="this is a top tooltip">
MON
</button>
Script code:
$scope.addvalue = function() {
var datevaluee=$scope.testDate23;
}

You need to pass the $event in ng-click function like below..
ng-click="addvalue($event)"
below will be the function implementation
$scope.addvalue = function(element) {
$scope.testDate23 = element.currentTarget.value; // this will return the value of the button
console.log( $scope.testDate23)
};

you can try this.
<button ng-click="addvalue(testDate23='SUN')">
button
</button>
or
<button ng-click="addvalue(testDate23='MON')">
btn2
</button>
Find fiddle Fiddle example
Hope it will help.

Button is an input for submitting data, not setting data.

You need use directive.
Live example on jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.getValue = function() {
$scope.value = $scope.testDate23;
}
});
myApp.directive('buttonValue', function() {
return {
restrict: 'A',
scope: {
buttonValue:"="
},
link: function(scope, element, attr) {
scope.$watch(function(){return attr.ngValue},function(newVal){
scope.buttonValue = newVal;
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<input ng-model="btnValue">
<button ng-value="{{btnValue}}" ng-click="getValue()" button-value="testDate23">
MON
</button>
<br>
<pre>testDate23= {{testDate23}}</pre>
<pre>value= {{value}}</pre>
</body>

If you want to set hardcoded value then use ng-init
<button type="button" ng-init="value=2" class="btn btn-primary ole two" data-toggle="tooltip" ng-click="addvalue()"
ng-model="testDate23" value="MON" id="buttonvalue" data-placement="top" data-original-title="this is a top tooltip">
MON
</button>
You can use value aywhere in your same template.

Related

Angular ng-click function requiring two clicks to take effect

I have the following directive
app.directive('replybox', function ($timeout, $window, $compile, $sce) {
var linkFn = function (scope, element, attrs) {
var exampleText= element.find('p');
var btn = element.find('button');
var windowSelection="";
scope.okOrCancel="None";
exampleText.bind("mouseup", function () {
scope.sel = window.getSelection().toString();
windowSelection=window.getSelection().getRangeAt(0);
if(scope.sel.length>0) {
scope.showModal = true;
scope.$apply();
}
});
btn.bind("click", function () {
if(scope.okOrCancel=='ok'){
range = windowSelection;
var replaceText = range.toString();
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = '<poper>' + replaceText + '<button type="button" class="btn btn-danger btn-xs">×</button></poper>';
var frag = document.createDocumentFragment(), child;
while ((child = div.firstChild)) {
frag.appendChild(child);
}
$compile(frag)(scope);
range.insertNode(frag);
scope.showModal=false;
}
if(scope.okOrCancel=='cancel'){
scope.showModal=false;
}
scope.selection="None";
scope.okOrCancel='None';
});
};
return {
link: linkFn,
restrict: 'A',
scope: {
entities: '=',
selection:'='
},
template: `<ng-transclude></ng-transclude>
<div class="modal fade in" style="display: block;" role="dialog" ng-show="showModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
{{sel}}
</div>
<div class="radio">
<div ng-repeat="x in entities">
<div class="radio">
<label>
<input type="radio" name="choice" ng-model="$parent.selection" ng-value = "x">
{{x}}
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ng-click="okOrCancel='ok'">
Ok
</button>
<button type="button" class="btn btn-primary" ng-click="okOrCancel='cancel'">
Cancel
</button>
</div>
</div>
</div>
</div>`,
transclude: true
};
});
So there is a modal in the template which contains an "Ok" and a "Cancel" button. There is an ng-click on these buttons which sets scope.okOrCancel to the appropriate value. btn binds to a button click and performs different actions depending on the state of scope.okOrCancel. When the "Ok" button is clicked everything works as expected. But the "Cancel" button requires two clicks in order for the modal to dissappear. I would think this would happen immediately within
if(scope.okOrCancel=='cancel'){
scope.showModal=false;
}
Can anyone tell me why the cancel button requires two clicks to close the modal?
Currently you have a mix of jQuery and angularjs for your ok and cancel click. Probably that is the reason to require two clicks to take effect.
If I were you, I would have write click like below:
Template:
<div class="modal-footer">
<button type="button" class="btn btn-primary" ng-click="okClick()"> Ok </button>
<button type="button" class="btn btn-primary" ng-click="cancelClick()"> Cancel </button>
</div>
In JS:
scope.okClick = function() {
range = windowSelection;
var replaceText = range.toString();
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = '<poper>' + replaceText + '<button type="button" class="btn btn-danger btn-xs">×</button></poper>';
var frag = document.createDocumentFragment(), child;
while ((child = div.firstChild)) {
frag.appendChild(child);
}
$compile(frag)(scope);
range.insertNode(frag);
scope.showModal=false;
}
scope.cancelClick = function() {
scope.showModal=false;
}
scope.selection="None";
scope.okOrCancel='None';
I hope this helps you!
Cheers
Completely agree with varit05's answer. Most likely it's because you do not trigger digest cycle in the click event handler. But in any way, the point is: it's not very good idea to mix jquery and angular stuff, unless: a) you absolutely sure it's necessary; b) you understand very well what you're doing and why; otherwise it will lead to such an unexpected consequences.
Just another a small addition. Another problem is here:
$compile(frag)(scope);
range.insertNode(frag);
The correct approach would actually be to insert new nodes into real DOM and only then $compile() them. Otherwise, any directives with require: "^something" in the DOM being inserted will fail to compile because they would not be able to find necessary controllers in upper nodes until new nodes actually make it to the "main" DOM tree. Of course, if you absolutely sure you don't have that then you can leave it as is and it will work... But then the problem will just wait out there for its "finest hour".

How to modify value on DOM button?

How to modify text on one specific DOM object? Tried the following code but ended up changing for all the DOM text. It changes all the {{content}} values not only 'b1'.
myfunc () {
$scope.content="nothing";
angular.element(document.getElementById('b1')).scope().content ='something';
}
Here is the html:
<button id="b1" type="button" ng-click="myfunc($event)">
{{content}}
</button>
<button id="b2" type="button" ng-click="myfunc($event)">
{{content}}
</button>
You should not use angular.element or do any DOM manipulation whatsoever anywhere else than in directives. What you want to do here is define $scope.contents as an array / object and then update only the index you want:
$scope.contents = Array(2).fill('nothing');
$scope.updateButton = function(index) {
$scope.contents[index] = 'something';
};
As for your template:
<button type="button" ng-click="updateButton(0)">{{ contents[0] }}</button>
<button type="button" ng-click="updateButton(1)">{{ contents[1] }}</button>

ng-click of angularJS is not displaying anything when buttons are clicked

angular js code:
appModule.controller('dcrlistingCtrl', ['$scope','$modal','$state','$rootScope','loginService', 'servicePOST', 'appConstants','sessionService', '$http',
function($scope,$modal,$state,$rootScope,loginService, servicePOST, appConstants,sessionService, $http) {
$scope.doctors = function() {
alert("Doctors");
};
$scope.pharmacists = function() {
alert("pharmacists");
};
$scope.stockists = function() {
alert("pharmacists");
};
alert("trial");
$scope.contact="Doctors";
$scope.doctors=
[
{"patch":"BARIJPUR", "doctor":["RAMA SENA", "SMRITI IRANI","JAGDISH NAIR"]},
{"patch":"Anna", "doctor":["ASHISH NAIK", "SMRITI IRANI", "SAIRAJ NAIK"]},
{"patch":"Peter","doctor":["RATAN PANDEY", "RAMAN SHIVOLKAR"]}
];
}])
html code:
<button type="button" class="btn btn-primary " ng-click=="doctors()"><b>Doctor</b></button>
<button type="button" class="btn btn-primary " ng-click=="pharmacists()" ><b>Pharmacist</b></button>
<button type="button" class="btn btn-primary " ng-click=="stockists()" ><b>Stockist</b></button>
any angularJS experet here? need help!
the alert("trial"); is shown!
But when i click these buttons, no alert is shown!
why is that so?
any help and advice or changes are appreciated!
Get rid of the double equals after each ng-click.
The following:
ng-click=="stockists()"
should be
ng-click="stockists()"
The alert("trial") is being shown because it is not within the scope
of any click function of yours rather in the scope of controller where
the alert("trial") gets called once you are into the view which has
that particular controller. And, the matter of fact where your click
function is not working is because you have got 2 equals(==) in
ng-click.
<button type="button" class="btn btn-primary " ng-click="doctors()"><b>Doctor</b></button>
<button type="button" class="btn btn-primary " ng-click="pharmacists()" ><b>Pharmacist</b></button>
<button type="button" class="btn btn-primary " ng-click="stockists()" ><b>Stockist</b></button>

Best way to create a reusable modal window in angularjs

I am using html5, angularjs, bootstrap. So each one of them gives many options to create a modal window. Whole of my website has 2 things, one is confirmation dialog or form dialog. So which is the best reusable approach. Should i use html5 or create a directive ?
As mentioned in the comments ui-bootstrap Modal is very useful.
Just for an example here is a factory for confirm modal that you can extend according to your use case:
yourApp.factory("dialog", ["$modal",
function($modal) {
var dialogService = {
confirm: function(options) {
var modalInstance = $modal.open({
templateUrl: 'partials/confirm-modal.html',
controller: ['$scope',
function($scope) {
$scope.header = options.header;
$scope.body = options.body;
$scope.confirmText = options.confirmText || "Close";
$scope.cancelText = options.cancelText || "Confirm";
$scope.hideCancelButton = options.hideCancelButton;
$scope.cancel = function() {
modalInstance.dismiss('cancel');
};
$scope.confirm = function() {
modalInstance.close();
};
}
]
});
return modalInstance.result;
}
}
}
])
And here is your template:
<div class="modal-header">
<button type="button" data-dismiss="modal" aria-hidden="true" class="btn close" ng-click="cancel()">×</button>
<h4 id="noteLabel" class="modal-title">{{header}}</h4>
</div>
<div class="modal-body">
<p ng-bind-html="body" style="font-size: 16px"></p>
</div>
<div class="modal-footer">
<button ng-show="!hideCancelButton" class="btn btn-default" ng-click="cancel()">{{cancelText}}</button>
<button ng-click="confirm()" class="btn btn-primary">{{confirmText}}</button>
</div>

ng-model is not updated in ng-if

I'm failing to retrieve the actual value of my selected option (ng-model=filter) in my select html bloc.
Note that if I don't set $scope.filter then $scope.filter stay undefined even if I select an option in the dropdown list.
My html template, filters.html :
<div ng-if="!showFilterTemplatePlz">
<button class="btn btn-primary" ng-click="showFilterTemplate()" type="button">Add Filter</button>
</div>
<div ng-if="showFilterTemplatePlz" class="inline">
<button class="btn btn-primary" ng-click="closeFilters()" type="button">Close filters</button>
<label>filters</label>
<select ng-model="filter" ng-options="filter.name for filter in filterOptions" class="form-control">
</select>
<p>{{filter.name}}</p>
<button ng-click="addFilter()" id="addFilterButton" class="btn btn-primary btn-sm btn-default" type="button"><i class="fa fa-plus"></i> Add</button>
</div>
In my directive:
.directive('filters', ['retrieveStaticDatasService','usersService', function(datasService, usersService) {
return {
restrict: 'E',
scope: false,
controller: function ($scope) {
/* init */
$scope.filterOptions = [
{name: "languages"},
{name: "nationality"},
{name: "location"}
];
$scope.filter = $scope.filterOptions[0];
/* end init */
$scope.showFilterTemplate = function(){
$scope.showFilterTemplatePlz=true;
}
$scope.closeFilters = function(){
$scope.showFilterTemplatePlz=false;
}
$scope.addFilter = function(){
console.log("filter to add : " + $scope.filter.name);
}
},
templateUrl: '/partials/components/filters.html'
}
}])
Result :
I can see the actual value appears in my html but i will always show "languages" for$scope.filter.name in my console, whatever option I selected! I took a screenshot to show you : http://hpics.li/4a37ae3
Thanks for your help.
[Edit : I made some test and my model are setted and updated only if they are not inside the "<div ng-if="..."></div>"]. Is it not allowed to put a ng-if directly in the directive?
Answer : Angularjs ng-model doesn't work inside ng-if
I found the solution, the problem was that ng-if creates a child scope. So I changed filter to $parent.filter in
<select ng-model="$parent.filter" ng-options="option.name for option in filterOptions" class="form-control">
</select>
I think you are confusing it by having to objects named 'filter'. You might be overwriting the ng-options object rather than your controller one.
Try changing to
<select ng-model="filter" ng-options="option.name for option in filterOptions" class="form-control"></select>
<p>{{filter.name}}</p>
<button ng-click="addFilter()" id="addFilterButton" class="btn btn-primary btn-sm btn-default" type="button"><i class="fa fa-plus"></i> Add</button>

Resources