我是Angular Js的新手。
是否可以将 RestaurantController 的范围转发到 MenuController 代码
示例: -
angular.module('restaurants').controller('RestaurantController', ['$scope',
function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
}
]);
我在菜单控制器中将餐厅ID指定为新范围,如下所示
angular.module('menus').controller('MenuController', ['$scope',
function($scope) {
$scope.currentrestaurantid= $scope.restaurantid;
alert($scope.currentrestaurantid); // showing Null
}
]);
餐厅ID不是坚持的。老实说,我觉得有些东西是缺失的。
如何从菜单控制器获取ID到菜单控制器?
答案 0 :(得分:1)
尝试继承
angular.module('restaurants', []);
angular.module('menus', ['restaurants']);
angular.module('restaurants').controller('RestaurantController', function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
});
angular.module('menus').controller('MenuController', ['$scope','$controller',
function($scope, $controller) {
$controller('RestaurantController', {$scope: $scope});
$scope.currentrestaurantid= $scope.restaurantid;
}
]);
工作fiddle
答案 1 :(得分:1)
我建议使用rootScope来做到这一点。
使用$ broadcast通知其他控制器第一个控制器范围的变化。
$rootScope.$broadcast("restIDUpdated", {
restaurant: $scope.restaurantid
});
使用$ on在第二个控制器中接收有关第一个控制器中发生的事件的通知。
$scope.$on("restIDUpdated", function (event, args) {
$scope.restaurant = args.restaurant;
});
有一个例子here
尝试这样的事情。
angular.module('restaurants').controller('RestaurantController', function($scope) {
$rootScope.$broadcast("restIDUpdated", {
restaurantid: 435scvcxvbrcvbnvn
});
});
angular.module('menus').controller('MenuController', ['$scope','$controller',
function($scope, $controller) {
$controller('RestaurantController', {$scope: $scope});
$scope.$on("restIDUpdated", function (event, args) {
$scope.currentrestaurantid= args.restaurantid;
});
}
]);
但说实话我不确定这个机制是否适用于两个不同的角度应用程序,我知道它使用相同的模块,但不确定使用两个不同的模块会发生什么,但看看{{ 3}}
答案 2 :(得分:1)
我经常使用的模式是创建一个角度服务并将其注入我想与之共享数据的控制器中。像这样......
angular.module('restaurants', []);
angular.module('menus', ['restaurants']);
angular.module('restaurants').service('RestaurantService', function() {
this.restaurantid = "435scvcxvbrcvbnvn";
});
angular.module('restaurants').controller('RestaurantController', function($scope, RestaurantService) {
$scope.restaurantid = RestaurantService.restaurantid;
});
angular.module('menus').controller('MenuController', function($scope, $controller, RestaurantService) {
$scope.currentrestaurantid = RestaurantService.restaurantid;
});
答案 3 :(得分:1)
如上所述,可注射服务作为您的情况的通用方式。
但是我想用更好的方式指出,使用标记和controller as
(docs)表达式。
例如,您有以下控制器:
.controller('RestaurantController', function($scope) {
$scope.restaurantid="435scvcxvbrcvbnvn";
})
并且您可以将其绑定到范围中的变量:
<div ng-controller="RestaurantController as restaurant">
<div ng-controller="MenuControllerOrAnyOther">
restaurant id = {{restaurant.restaurantid}}
</div>
</div>
<强>说明强>
如果仅在标记中需要restaurantid
,例如
<button ng-click="select(restaurant.restaurantid)">
如果你想在js代码中使用restaurantid
(你应该使用可注射服务),这看起来很难看:
var restaurantid = $scope.$eval('restaurant.restaurantid');