kennechu kennechu - 1 month ago 6x
Javascript Question

Get the value of an Agular button and log them into the console

I have a very basic question.

I have two buttons in my view, what I want to do is to assign the value of each of those buttons to a variable in my controller ("$scope.buttonValue", for example) so every time I click on each I can log the value in the console and give the $scope variable a value depending on the button I click.

Basic Angular Buttons

<div class="btn-group" ng-init="showData = 1">
<button ng-model="showData" type="button" ng-class='{"btn btn-primary": showData == 1, "btn btn-white": showData != 1}' ng-click="showData = 1">One</button>
<button ng-model="showData" type="button" ng-class='{"btn btn-primary":showData == 2, "btn btn-white": showData != 2}' ng-disabled="!loadViewOne" ng-click="showData = 2">Two</button>

Basic Plunker.

I'm new to angular and js so I need some help on this to understand more stuff.

The buttons have some validations, and I think I'm already giving a value to showData, but I dont know how to pass that to a $scope in a controller.


Here is how I would change your Plunkr example code to work.

See it on Plunkr

First of all, I would change showData to be a function that the ng-click expressions call. This allows you to actually respond to the click of the button by doing stuff in your controller. In my code, this function just sets a separate property on the scope, which I called data, that is used for other logic like the button classes.

Here it is as a working example:

var app = angular.module('app', [])
  .controller('MainCtrl', MainCtrl);

function MainCtrl($scope, $timeout) {
  $ = 1;
  $scope.loadViewBrands = true;

  $scope.showData = function(num) {
    $ = num;

  $scope.summaryCall = function() {
    $scope.summaryCallText = 'summaryCall() was run, and data = ' + $;
    $timeout(function() {
      $scope.summaryCallText = '';
    }, 1000);
<link href="" rel="stylesheet" />
<script src=""></script>
<div ng-app="app">
  <div ng-controller="MainCtrl">
    <h1>Basic Angular Buttons</h1>
    <div class="btn-group">
      <button type="button" ng-class="{'btn btn-primary': data == 1, 'btn btn-white': data != 1}" ng-click="showData(1)">One</button>
      <button type="button" ng-class="{'btn btn-primary':data == 2, 'btn btn-white': data != 2}" ng-disabled="!loadViewBrands" ng-click="showData(2); summaryCall()">Two</button>
    <p>data = {{data}}</p>
    <div class="alert alert-info" ng-if="summaryCallText">