我定义了一个 Controller ,范围内有一些变量。我可以知道是否有办法直接在 Controller 外部为范围变量赋值(不是通过 ng-model
)?另外,我可以直接在 <script>
的某处调用 Controller 的功能吗?网页元素(而不是使用 ng-click
)?
谢谢!
干杯, 克里斯
最佳答案
angular 中的 Controller 定义实际上是一个类而不是对象。在 HTML 中引用 Controller 的每个地方,在编译阶段,angular 使用定义的 Controller 类创建一个新的 Controller 对象。因此,您可以引用具有相同 Controller 类的多个作用域。
总是有一个与 Controller 关联的范围,并且所有变量都绑定(bind)到该范围。您可以通过调用类似的东西来访问特定 html 元素的范围
var scope = angular.element("#myelement").scope();
//use the scope....
如果您让我们知道您尝试从 Controller 外部访问作用域的原因,那也很好。
更新
这是引导选项卡组件...您可以将其用作
<tab>
<pane title="tab1"><pane>
<pane title="tab2"></pane>
</tabs>
这与存在于 http://angularjs.org/ 的同一个主页.. 我刚刚将其更新为在选项卡更改时广播事件。
var directives = angular.module('myApp.directives', []);
directives.directive('tabs', function () {
return {
restrict:'E',
transclude:true,
scope:{},
controller:function ($scope, $element, $rootScope) {
var panes = $scope.panes = [];
$scope.select = function (pane) {
angular.forEach(panes, function (pane) {
pane.selected = false;
});
pane.selected = true;
$rootScope.$broadcast("tabChanged", pane.title);
}
this.addPane = function (pane) {
if (panes.length == 0) $scope.select(pane);
panes.push(pane);
}
},
template:'<div class="tabbable">' +
'<ul class="nav nav-tabs">' +
'<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">' +
'<a href="" ng-click="select(pane)">{{pane.title}}</a>' +
'</li>' +
'</ul>' +
'<div class="tab-content" ng-transclude></div>' +
'</div>',
replace:true
};
});
directives.directive('pane', function () {
return {
require:'^tabs',
restrict:'E',
transclude:true,
scope:{ title:'bind' },
link:function (scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
template:'<div class="tab-pane" ng-class="{active: selected}" ng-transclude>' +
'</div>',
replace:true
};
});
这会在选项卡更改时调度一个事件。
关于javascript - 有没有办法直接在 Angularjs 中与 Controller 和范围进行交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973568/