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

Updating directive based on change in service value AngularJS

我目前有一个基本的应用程序,它在侧边栏导航栏中有一个名称列表,该名称列表是通过 json 对我的服务器的调用填充的。当用户单击侧边栏中的名称时,它会将 nameService 更新为用户单击的名称。

当 nameService 更新时,我想对 name-data 视图进行另一个 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 放在手表下面,但似乎没有任何作用。

是否有某种形式的 angular 魔术可以用来在从侧边栏中包含的名称列表中选择新用户时动态发起新的 json 调用?

也许 angular 事件广播?

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

        }
    };  
}]);