根据服务值AngularJS的变化更新指令



我目前有一个基本的应用程序,它在侧边栏导航中有一个名称列表,该列表是通过对服务器的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调用?

也许是角事件广播?

将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); 
}
};  
}]);

最新更新