数据模型更改时 ngSwitch 不会更新

ngSwitch does not update when data model change

我是 Angular 的新手,正在尝试编写一些简单的应用程序。 我在使用 ngSwitch 按需切换相应指令时遇到问题,如下所示。

html 标记:

主要html文件: 指令一:

.directive('directiveOne',function(){
      return {
      restrict:"AE",
      replace:true,
      template:"<div>this is directive one</div>",
      controller:"Dir1Controller",
      }
})
.directive('directiveTwo',function(){
      return {
      restrict:"AE",
      template:"<div>this is directive 2</div>,
      controller:"Dir2Controller"
      }
})

以及在控制器之间共享数据的服务。

.factory('ShareDataFct',function($rootScope){
      var srv={};

      srv.setValue=function(value){
      this.srv.var = value;
      $rootScope.$broadcast('varChanged');

      }
      return srv;
})

最后是指令的 3 个控制器。

.controller('MainController',function($scope,ShareDataFct){
            $scope.$watch('varChanged',function(){
            $scope.myvar=ShareDataFct.var;
            })
      })
.controller('Dir1Controller',function($scope){
  //nothing to do here yet
      })
  .controller('Dir2Controller',function($scope){
  //nothing to do here yet
  })

然后我尝试更改 ShareDataFct var,但视图 (ng-switch) 不会更改以根据 myvar 更改显示指令。 请指教。谢谢。

其实你有几个问题。

1st : 你正在使用 $rootscope.$broadcast 并尝试用 $watch 捕捉结果。

你应该使用 $scope.$on 而不是 watch。

2nd : 你不应该尝试使用 $rootscope, $broadcast 和 $watch 来更新变量。如果您尝试这样做,那您就错了。

怎么做?只需直接从您的工厂共享 var。

app.factory('ShareDataFct',function(){
  var srv={};
  srv.data={};
  srv.data.value="";//init your value here
  return srv;
})

在您的控制器中,您可以像这样绑定它:

  .controller('MainController',function($scope,ShareDataFct){
        $scope.data=ShareDataFct.data;
  })

在您看来,可以这样使用它:

  <div>{{data.value}}</div>

在你的 ng-switch 中:

  <div ng-switch on="data.value">
     <div ng-switch-when="Test"> This is a test</div>
     <div ng-switch-when="TestAgain"> This is a test ... again !</div>
  </div>

请注意,重要的是共享对象而不是原始值,因为更新值会删除引用并且不会在应用程序的其他部分更新。

这是一个有效的 plunker 示例。

希望对您有所帮助。

编辑:添加了 plunker