我是Angular的新手并尝试编写一些简单的应用。 我有问题使用ngSwitch根据需要切换相应的指令。
html标记:
主html文件: 指令1:
.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更改显示指令。 请指教。谢谢。
答案 0 :(得分:0)
实际上你有几个问题。
1st:你正在使用$ rootscope。$ broadcast并尝试用$ watch来捕获结果。
你应该使用$ scope。$ on而不是watch。
第二:你永远不应该尝试使用$ 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