我目前有一个基本应用程序,其中包含从json调用填充到我的服务器的侧栏导航中的名称列表。当用户单击侧栏中的名称时,它会将nameService更新为用户单击的名称。
当nameService更新时,我想命名数据视图,根据用户点击的名称,使另一个json调用服务器以获取正确的json文件。
我无法根据服务中包含的值更改来更新视图。我在AngularJS应用程序中有两个控制器和一个服务,如下所示:
app.js
var app = angular.module("myapp", ['ui.bootstrap']);
app.directive("sideBar", ['$http', 'nameService', function($http, nameService) {
return {
restrict: 'E',
templateUrl: "views/sidebar.html",
controller: function($scope) {
$scope.updateName = function(name) {
nameService.setName(name);
};
$http.get('../data/names.json').
success(function(data, status, headers, config) {
$scope.names = data;
});
}
};
}]);
app.directive("nameData", ['$http', 'nameService', function($http, nameService) {
return {
restrict: 'E',
templateUrl: "views/name-data.html",
controller: function($scope) {
$scope.service = nameService;
var path = "../data/" + $scope.service.name + ".json";
$http.get(path).success(function(response) {
$scope.info= response.info;
});
}
};
}]);
app.service('nameService', ['$http', function($http) {
this.name = "TestName";
this.setName = function(name) {
this.name = name;
};
this.getName = function() {
return this.name;
};
}]);
每当用户点击侧栏导航并更新nameService.name属性时,如何更新nameData视图?
我尝试将$scope.service.name
放在手表下,但似乎没有做任何事情。
当从我的边栏中包含的名单中选择新用户时,是否有某种形式的角度魔法可用于动态制作新的json?
答案 0 :(得分:1)
也许角度事件广播?
将rootScope添加到服务并在名称更改时广播事件:
app.service('nameService', ['$http','$rootScope', function($http,$rootScope) {
this.name = "TestName";
this.setName = function(name) {
this.name = name;
$rootScope.$broadcast('nameService-nameChanged');
};
this.getName = function() {
return this.name;
};
}]);
然后在指令控制器范围内绑定到该事件:
app.directive("nameData", ['$http', 'nameService', function($http, nameService) {
return {
restrict: 'E',
templateUrl: "views/name-data.html",
controller: function($scope) {
$scope.service = nameService;
//turned your load mechanism in to a function
$scope.loadNameData = function(){
var path = "../data/" + $scope.service.name + ".json";
$http.get(path).success(function(response) {
$scope.info= response.info;
});
}
//initial load
$scope.loadNameData();
//subscribe to broadcast event, this will call $scope.loadNameData when the 'nameService-nameChanged' event is broadcast
$scope.$on('nameService-nameChanged',$scope.loadNameData);
}
};
}]);