问题描述
我是新手对Aβ,我试图与另一个控制器共享$ scope.showdropdown指令,使得第二控制器可以调用这个指令在它的身上。
I'm newbie to AJs, and I'm trying to share $scope.showdropdown directive with another controller so that the second controller can call this directive in its body.
.controller('firstCtrl', function($scope){
$scope.showdropdown = false; // this is part of this controller
})
.controller('secondCtrl', function($scope){
if(username and pass correct){
$scope.showdropdown = true; // I want to call this here, but I can't do it bcoz its not part of the same controller!!!
}
})
我试过各种事情,工厂等,并没有运气
有人可以告诉我怎么才能做到这一点,请!
I tried all sorts of thing, factory etc. and had no luckCan someone show me how can this be done please!
推荐答案
如果这是你需要的控制器(即没有的功能,验证或其他模型逻辑)之间共享只简单的数据,你可以使用值
服务:
If it's only simple data that you need to share between the controllers (ie no functionality, validation, or other model logic), you can use a value
service:
.controller('firstCtrl', function($scope, myVal){
$scope.shared = myVal; // 'shared' on scope now references value service
$scope.shared.showdropdown = false;
})
.controller('secondCtrl', function($scope, myVal){
$scope.shared = myVal;
if(username and pass correct){
$scope.shared.showdropdown = true; // updates myVal value
}
})
.value('myVal', {}) // register service, initializing with an object object
这个概念是一个工厂
或服务
服务类型和实现,同样是非常相似的。与其中的一个去,如果你需要共享的功能,而不仅仅是数据。工厂例如:
The concept is the same for a factory
or service
service type and the implementation is very similar. Go with one of these if you need to share functionality, not just data. Factory example:
.controller('firstCtrl', function($scope, MyFactory){
$scope.shared = MyFactory;
...
})
.controller('secondCtrl', function($scope, MyFactory){
$scope.shared = MyFactory;
...
})
.factory('MyFactory', function(){
var obj = {
//showdropdown: false
};
obj.someFunc = function(){};
return obj;
})
这篇关于如何共享$作用域属性,而不是它在angularjs两个控制器之间的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!