2012-11-21 59 views
0

我有this fiddle example我試圖在居住在不同作用域的ng-repeat中設置一個值。這是我正在努力解決的一個更大問題的一個非常基本的例子。基本上我需要在ng-repeat中設置一個變量,這樣angular會相應地更新模板。問題在於該模板位於子控制器中。所以我使用$控制器注入能夠訪問變量。但是,更新此變量不會導致模板更新。即使我做了一個範圍$ apply()。有人有主意嗎?我不確定另一種方式來做到這一點...從角度js中的父作用域更新子作用域的模板

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

myApp.directive("custdirective", function() { 
    return { 
     restrict: 'A', 
     scope: 'false', 
     link: function(scope, element, attr) { 
      element.on("click", function() { 
      anotherscope.addList(); 
      }); 
     } 
    } 
}); 

function AnotherController($scope) { 
    $scope.listtwo = new Array(); 
    $scope.addList = function() { 
     $scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
    } 
} 

function MyCtrl($scope, $controller, $rootScope) { 
    anotherscope = $rootScope.$new(); 
    $scope.anothercontroller = $controller(AnotherController, { 
     $scope: anotherscope 
    }); 
}​ 

要做到這一點正確,一個會創建一個服務。我做了正確的方式更新的小提琴做到這一點here或:約

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

myApp.factory("mySharedService", function($rootScope) { 
    var sharedService = {}; 
    sharedService.message = ''; 

    sharedService.prepForBroadcast = function() { 
     this.message = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
     this.broadcastItem(); 
    }; 
    sharedService.broadcastItem = function() { 
     $rootScope.$broadcast('handleBroadcast'); 
    }; 

    return sharedService; 

}); 

myApp.directive("custdirective", function() { 
    return { 
     restrict: 'A', 
     scope: 'false', 
     link: function(scope, element, attr) { 
      element.on("click", function() { 
       debugger; 
       scope.handleClick(); 
      }); 
     } 
    } 
}); 

function AnotherController($scope, sharedService) { 
    $scope.listtwo = new Array(); 
    $scope.addList = function() { 
     $scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
    } 

    $scope.$on('handleBroadcast', function() { 
     $scope.listtwo = sharedService.message; 
    $scope.$apply(); 
    }); 
} 

function MyCtrl($scope, sharedService) { 
    $scope.handleClick = function() { 
     sharedService.prepForBroadcast(); 
    }; 
} 


MyCtrl.$inject = ['$scope', 'mySharedService'];   

AnotherController.$inject = ['$scope', 'mySharedService'];​ 

回答

3

傳遞範圍一樣,是有點靠不住的,並且幾乎肯定會打破你的角度應用程序的可測試性。

我認爲你最好在creating a service之間調整你的控制器和你的指令之間的變化。該服務將包含您希望更新的數組或您希望從您的指令中調用的函數。

恐怕很難寫出這樣一個服務的例子,因爲我真的不明白你的最終目標是什麼。

+0

我在等待答案時開始研究角度,並提出了這個人[這裏](http://jsfiddle.net/ADukg/1412/)。似乎做我需要它做的事情。謝謝你的提示。 – yaegerbomb

相關問題