0

I'm using angular and added a button in index.html:

<button ng-controller = "studentCtrl" ng-click="$emit('update')">refresh</button>

When clicked, the model has been updated but the view not, even $digest has been executed. When I add the same button in the templateURL of studentCtrl, it works fine. I try to move the button to ng-view div but it still fails, so can anyone tell me the difference?

The templateURL for studentCtrl is

<tr ng-controller="studentCtrl" ng-repeat="student in students">
    <td>{{student.name}}</td>
    <td><button ng-click="$emit('update')">refresh</button></td>
</tr>

and the studentCtrl is

.controller('studentCtrl', ['$scope', 'baseDataUrl', '$http', '$timeout', 
    function($scope, baseDataUrl, $http, $timeout) {
        $scope.update = function() {
        $http.get(baseDataUrl).then(function(res) {
           $scope.students = res.data;
        });
     };
     $scope.update();

     //when switch to student app, get all students data first
     $scope.$on("update", function() {
         //for test
         $scope.students = [];
     });
  }]);
Bowdzone
  • 3,827
  • 11
  • 39
  • 52
Sladar
  • 65
  • 9
  • You can read more here http://stackoverflow.com/questions/14502006/working-with-scope-emit-and-on – Anand G Dec 04 '15 at 10:12

2 Answers2

0

$emit() dispatches the event upwards through the scope hierarchy, from child to parent.It should use from child controller to parent controller, you can simply call update method for click event.

<button ng-controller = "studentCtrl" ng-click="update()">refresh</button>
  • In fact the event has been listened successfully, only the view hasn't been updated, i mean the view binded with $scope.students. Also your code doesn't work, the behavior is same, the $scope.students has changed but the view hasn't. Also I want to know how you define scope hierarchy, or what can i search to study this. – Sladar Dec 05 '15 at 12:16
0

use $scope.$apply() to update the view. $emit and $broadcast is used as delegate, works based on some event-handler concept between controllers, That's not required I guess in your example , so you can simply write your controller

.controller('studentCtrl', ['$scope', 'baseDataUrl', '$http', '$timeout', 
function($scope, baseDataUrl, $http, $timeout) {
   // define your scope varibales
    $scope.students = [];

    $scope.update = function() {
        /// update the students collection
       };
  }]);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213