fourth
fourth

Reputation: 739

Why my onclick doesn't work?

I am new on this field, and have tried this for a long time. You can see my simple version here: https://plnkr.co/edit/YeahrG28bT2izX8gMKor?p=preview

Could you tell me why my onclick here doesn't work? My button is the 2signUp botton, Thanks!

js:

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

app.controller('mainControl', function($scope) {
  $scope.logged = false;
  $scope.visiter = true;
  var sub1 = document.getElementsByClassName("haha")[0];
  sub1.onclick=function(){
    $scope.logged = !$scope.logged;
  }
})

html:

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="MainViewController.js"></script>
</head>
<body ng-controller="mainControl">
        <div ng-show="logged">
            <button>1Sign Up</button>
            <button>Log In</button>
        </div>
        <div ng-show="visiter">
            <button class="haha">2Sign Up</button>
            <button>Log In</button>
        </div>
        <div ng-show="logged">
          hello
        </div>

</body>

Upvotes: 1

Views: 1043

Answers (1)

Logan H
Logan H

Reputation: 3423

Use the Angular way of handling click events, don't use any document.getElementById() jazz when you have angular to do the work for you.

This is why you should let angular handle it

Data Binding

Data-binding is an automatic way of updating the view whenever the model changes, as well as updating the model whenever the view changes. This is awesome because it eliminates DOM manipulation from the list of things you have to worry about.

https://angularjs.org/

Use Angular's ngClick

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

app.controller('mainControl', function($scope) {
  $scope.logged = false;
  $scope.visiter = true;
  $scope.signup = function() {
    $scope.logged = !$scope.logged;
    alert("ran the function");
  }
})
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>

<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="MainViewController.js"></script>
</head>

<body ng-controller="mainControl">
  <div ng-show="logged">
    <button>1Sign Up</button>
    <button>Log In</button>
  </div>
  <div ng-show="visiter">
    <button id="haha" ng-click="signup()">2Sign Up</button>  <!-- use ngClick here! -->
    <button>Log In</button>
  </div>
  <div ng-show="logged">
    hello
  </div>
</body>

</html>

Upvotes: 4

Related Questions