我有两个Angular控制器:
function Ctrl1($scope) {
$scope.prop1 = "First";
}
function Ctrl2($scope) {
$scope.prop2 = "Second";
$scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}
我不能在Ctrl2中使用Ctrl1,因为它是未定义的。然而,如果我试图像这样传递它。
function Ctrl2($scope, Ctrl1) {
$scope.prop2 = "Second";
$scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}
我得到一个错误。有人知道怎么做吗?
做
Ctrl2.prototype = new Ctrl1();
也失败了。
注意:这些控制器彼此之间不是嵌套的。
啊,吃点这种新东西作为另一种选择。它是本地存储,在angular工作的地方工作。不客气(但真的,谢谢那个家伙)
https://github.com/gsklee/ngStorage
定义默认值:
$scope.$storage = $localStorage.$default({
prop1: 'First',
prop2: 'Second'
});
访问值:
$scope.prop1 = $localStorage.prop1;
$scope.prop2 = $localStorage.prop2;
存储值
$localStorage.prop1 = $scope.prop1;
$localStorage.prop2 = $scope.prop2;
记住在应用中注入ngStorage,在控制器中注入$localStorage。
第二种方法:
angular.module('myApp', [])
.controller('Ctrl1', ['$scope',
function($scope) {
$scope.prop1 = "First";
$scope.clickFunction = function() {
$scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
};
}
])
.controller('Ctrl2', ['$scope',
function($scope) {
$scope.prop2 = "Second";
$scope.$on("update_Ctrl2_controller", function(event, prop) {
$scope.prop = prop;
$scope.both = prop + $scope.prop2;
});
}
])
Html:
<div ng-controller="Ctrl2">
<p>{{both}}</p>
</div>
<button ng-click="clickFunction()">Click</button>
欲了解更多细节,请参阅plunker:
http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview
我倾向于使用价值观,乐意任何人讨论为什么这是一个坏主意。
var myApp = angular.module('myApp', []);
myApp.value('sharedProperties', {}); //set to empty object -
然后按服务注入值。
在ctrl1中设置:
myApp.controller('ctrl1', function DemoController(sharedProperties) {
sharedProperties.carModel = "Galaxy";
sharedProperties.carMake = "Ford";
});
从ctrl2访问:
myApp.controller('ctrl2', function DemoController(sharedProperties) {
this.car = sharedProperties.carModel + sharedProperties.carMake;
});