【发布时间】:2017-09-22 16:04:52
【问题描述】:
我需要单击一个控制器中的一个按钮,并让它使用 AngularJS 在同级控制器中触发/运行一个函数。
在我的(非常简化的)示例中,我有一个标题组件和一个内容组件。我有两个按钮可以更改对象的颜色(但是,我的实际情况要复杂得多)。我需要能够从另一个组件调用这些相同的函数。
INDEX.HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<script id="header-template" type="text/ng-template">
<h1>HEADER</h1>
<button type="button" ng-click="model.makeRed()">Make Red</button>
<button type="button" ng-click="model.makeBlue()">Make Blue</button>
<br />
<br />
<pre>{{model}}</pre>
<hr />
</script>
<script id="content-template" type="text/ng-template">
<h2>Content</h2>
<div ng-class="model.colorme">Object to color</div>
<br />
<button type="button" ng-click="model.makeRed()">Make Red</button>
<button type="button" ng-click="model.makeBlue()">Make Blue</button>
<br />
<br />
<pre>{{model}}</pre>
</script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<header-component></header-component>
<content-component></content-component>
</div>
</body>
</html>
SCRIPT.JS
console.clear();
function headerController() {
var model = this;
model.test = "test header";
console.log(model);
}
function contentController() {
var model = this;
model.test = "test content";
model.makeRed = function() {
model.colorme = "red";
}
model.makeBlue = function() {
model.colorme = "blue";
}
console.log(model);
}
var app = angular.module("app", []);
app.component("headerComponent", {
template: $("#header-template").html(),
controllerAs: "model",
controller: [headerController]
});
app.component("contentComponent", {
template: $("#content-template").html(),
controllerAs: "model",
controller: [contentController]
});
STYLE.CSS
.blue { background-color: blue; color: white; }
.red { background-color: red; color: white; }
【问题讨论】:
-
你试过类似this的东西吗?
-
我使用组件和那些只是直接的控制器有关系吗?另外,我认为会有某种绑定方法而不是使用 $rootscope (我看到人们有时会推荐它)。
-
你有这两个组件的父组件吗?
-
@RichC :是的,它应该可以解决问题。可以使用angularjs组件绑定来共享函数或变量(使用
=绑定) -
@RichC : 当然,我现在就去做
标签: javascript angularjs