2015-12-04 21 views
0

我使用的角度,並添加index.html中的按鈕是什麼在角的區別:當在不同的文檔段執行同樣的功能

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

點擊時,該模型已被更新,但認爲不是,即使$digest已執行。當我在studentCtrltemplateURL中添加相同的按鈕時,它工作正常。我嘗試將按鈕移動到ng-viewdiv但它仍然失敗,所以任何人都可以告訴我區別嗎?

templateURLstudentCtrl

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

studentCtrl

.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 = []; 
    }); 
    }]); 
+0

你可以在這裏閱讀更多的http:// stackoverflow.com/questions/14502006/working-with-scope-emit-and-on –

回答

0

$發出()通過作用域層級向上調度的情況下,從小孩到parent.It應該從孩子使用控制器到父控制器,你可以簡單地調用點擊事件的更新方法。

<button ng-controller = "studentCtrl" ng-click="update()">refresh</button> 
+0

事實上,事件已被成功監聽,只有視圖沒有被更新,我的意思是與$ scope.students綁定的視圖。此外,您的代碼不起作用,行爲相同,$ scope.students已更改,但視圖沒有。另外我想知道你如何定義範圍層次結構,或者我可以搜索什麼來研究它。 – Sladar

0

使用$scope.$apply()來更新視圖。 $emit$broadcast作爲代表,作品基於控制器之間的一些事件處理的概念,這是不需要我猜你的榜樣,這樣你就可以輕鬆的寫控制器

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

    $scope.update = function() { 
     /// update the students collection 
     }; 
    }]);