我有一个正在使用 Angular 构建的应用程序,我有大约 8-10 个 View 需要构建。 所有 View 都有一个共享页脚,基于 View 和一组业务规则,我需要有条件地显示/隐藏页脚上的某些内容。
所以。 我有每个 View 的 Controller ,还有页脚的 Controller 。 我使用 ng-include 包含常见的页脚布局,其中我包含的 html 引用了 ng-controller 中的页脚 Controller 。
索引.html
<body ng-controller="MainCtrl as vm">
<p>Message from Main Controller '{{vm.mainMessage}}'</p>
<div ng-include="'commonFooter.html'"></div>
</body>
commonFooter.html
<div ng-controller="FooterCtrl as vm">
<p>Message from Footer Controller '{{vm.message}}'</p>
<p ng-show="vm.showSomthing">Conditional footer Content</p>
</div>
我希望每个 View Controller 确定页脚的状态以及特定内容是否隐藏。 (下面应该DisplaySomthingInFooter)
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.mainMessage= 'HEELO';
vm.shouldDisplaySomthingInFooter = true;
window.console.log('Main scope id: ' + $scope.$id);
});
然后我打算在 FooterController 中返回父 Controller 并提取特定设置以根据业务规则启用/禁用内容。
app.controller('FooterCtrl', function($scope) {
var vm = this;
vm.message = 'vm footer';
window.console.log('Footer scope id: ' + $scope.$id);
window.console.log('Footer parent scope id: ' + $scope.$parent.$id);
window.console.log('Footer grandparent scope id: ' + $scope.$parent.$parent.$id);
window.console.log('Footer grandparent scope name: ' + $scope.$parent.$parent.mainMessage);
window.console.log('Footer grandparent scope condition: ' + $scope.$parent.$parent.shouldDisplaySomthingInFooter);
vm.showSomthing = false; //how to pull from parent scope to bind the ng-show to a value set in the parent from within a ng-include?
});
我这里有这个例子: http://plnkr.co/edit/ucI5Cu4jjPgZNUitY2w0?p=preview
我发现,当我进入父范围以提取内容时,它会以未定义的形式返回,我不确定为什么。
通过检查scopeid,我可以看到范围嵌套到祖 parent 级别,我相信这是因为ng-include 在 View 范围下面添加了一个额外的范围层。
额外要点:如果我不必使用 $scope 对象并且可以坚持使用 var vm = this;
方式,那就更好了。但乞丐不能挑剔:)
app.controller('MainCtrl', function($scope) {
var vm = this;
提前非常感谢您。
最佳答案
如果将外部 Controller 的范围设置为 vm
,将内部 Controller 的范围设置为 foo
,那么您可以轻松地将它们分开并在内部 Controller 中引用 vm。
HTML:
<body ng-controller="MainCtrl as vm">
<p>Message from Main Controller '{{vm.mainMessage}}'</p>
<div ng-include="'commonFooter.html'"></div>
</body>
CommonFooter.html:
<div ng-controller="FooterCtrl as footer">
<p>Message from Footer Controller '{{footer.message}}'</p>
<p ng-show="vm.shouldDisplaySomethingInFooter">Conditional footer Content</p>
</div>
app.js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
var self = this;
self.mainMessage = 'Hello world';
self.shouldDisplaySomethingInFooter = true;
});
app.controller('FooterCtrl', function() {
var self = this;
self.message = 'vm footer';
});
注意:为了清晰起见并减少 View 和 Controller 之间的混淆,我将您的 var vm = this
重命名为 var self = this
。
预期输出:
关于javascript - AngularJS : ng-include and ng-controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27087730/