0

I am having problem with $rootScope. I am changing the value in "button" clicked event, but it's NOT changing in the directive.

HTML page shows "TEST" to start with, on button click, I am expecting to change to "CLICKED". What is the mistake? in my code, please help.

<html>
<script src="jquery.min.js"></script>
<script src="angular.js"></script>
<script>
       "use strict";
       var app = angular.module('myApp', []);

       app.run(function ($rootScope) {
                $rootScope.name = 'TEST';
       });

       app.controller('btnCtrl', function($scope, $rootScope){

       $("#Btn").click( function($rootScope) {
            alert('Btn clicked');
            $rootScope.name = 'CLICKED';
       });

     });

</script>
<body>
    <div ng-app="myApp">

        <b> {{name}} </b>  
        <p> Clcik button to change above text to "CLICKED", <u>not working why?</u></p> 

        <div ng-controller="btnCtrl" > 
            <input type="button" value="Button" id="Btn" />   
        </div>    
    </div>
</body>
</html>
Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51

1 Answers1

0

Use ng-click instead of binding the click event jquery-way. It should be <input type="button" value="Button" id="Btn" ng-click="assignNewName()" />. And inside your controller:

app.controller('myCtrl', function($scope, $rootScope) {
  $scope.assignNewName = function() {
    $rootScope.name = 'Foo';
  }
});
Roman Kolpak
  • 1,942
  • 21
  • 25
  • I am getting error **undefined is not a function** at _Scope.$apply (file:///C:/Users/in4i_000/Documents/angular.js:12049:23) _ – InFi Finesse Aug 26 '14 at 06:10
  • sorry, controller name should be "btnCtrl", not "myCtrl" in my example (assuming you copy-pasted the code). Check that and see if it fixes your errors. Also, seems like you need to go through the official tutorial to learn a bit more about angular to understand the concepts and use it correctly: https://docs.angularjs.org/tutorial. Also check egghead sreencasts, they are really helpful: https://egghead.io/ – Roman Kolpak Aug 26 '14 at 08:45