使用AngularJS在控制器中传递数据

时间:2016-03-23 18:51:36

标签: javascript angularjs

我的应用程序中有2个视图。我想将第一个视图输入传递给我的第二个视图占位符。我在

下创建了一项服务
.service('greeting', function Greeting() {

    var greeting = this;

greeting.message = 'Default';

})

.controller('LogonController', function LogonController(greeting) {
    var first = this;

    first.greeting = greeting;
})

.controller('VideoController', function VideoController(greeting) {
    var second = this;

    second.greeting = greeting;

});

及以下是我使用不同控制器的2个不同视图

<div ng-controller="LogonController as first">
    <form>
        <input type="text" data-ng-model="first.greeting.message" placeholder="{{ first.greeting.message }}"> //1ST VIEW
    </form>
</div>

<div ng-controller="VideoController as second">
    <h1>{{ second.greeting.message }}</h1>
<div> //2ND VIEW

在我输入输入之前,我希望在我的第一个表单视图中获得一个带有Default消息的占位符。

我将如何使其发挥作用。

1 个答案:

答案 0 :(得分:0)

也许您在测试此内容的任何浏览器都不喜欢您添加<div>的未关闭的VideoController

<div ng-controller="VideoController as second">
    <h1>{{ second.greeting.message }}</h1>
<div> <-- this should be a closing /div

这是一个工作版本:

<div ng-app="app">
    <div ng-controller="LogonController as first">
        <form>
            <input type="text" data-ng-model="first.greeting.message" placeholder="{{ first.greeting.message }}">
        </form>
    </div>

    <div ng-controller="VideoController as second">
        <h1>{{ second.greeting.message }}</h1>
    </div>
</div>

JS:

angular.module('app', [])
    .service('greeting', function Greeting() {
        var greeting = this;
        greeting.message = 'Default';
    })
    .controller('LogonController', function LogonController(greeting) {
        var first = this;
        first.greeting = greeting;
    })
    .controller('VideoController', function VideoController(greeting) {
        var second = this;
        second.greeting = greeting;
    });

Working JSFiddle with above