在AngularJS组件

时间:2017-10-24 09:49:59

标签: javascript angularjs

我有这个组件:

<div class="rtm-nav">
    <div ng-app>    
    <form ng-submit="$ctrl.submit">
        <label>From:
            <input type="text" name="input" ng-model="$ctrl.from">
        </label>
        <label>To:
            <input type="text" name="input" ng-model="$ctrl.to">
        </label>
        <input type="submit" id="submit" value="Apply" />
    </form> 
    </div>
</div>

这是控制器:

const rtmNav = {
    bindings: {
        from:'<',
        to:'<',
        submit: '&'
    },
    controller: angular.noop,
    templateUrl: require('./rtmNav.html')
}

export default rtmNav;

主页的控制器:

class DemandCtrl {
    constructor(ChartDataService) {
        this.ChartDataService = ChartDataService;
        debugger;
        this.dataa = {
            from: '10/01/2017',
            to:  '10/03/2017'
        };
        this.submit = () => {
            console.log('tesst');
        };
    }

    $onInit() {
        getData.call(null, this);       
    }
}

function getData(DemandCtrl) {
    debugger;
    DemandCtrl.ChartDataService.getData(DemandCtrl.dataa).then(result => {
        DemandCtrl.result = result.data;
        getChart(result.data);
    }).catch((e) => {
        console.log(e);
    });
}

...

DemandCtrl.$inject = ['ChartDataService'];

export const Demand = {
    bindings: {
        data: '<'
    },
    templateUrl: demandPageHtml,
    controller: DemandCtrl
};

这是主页的html:

<div class="demand page">   
    <rtm-header title="Demand" icon="fa fa-line-chart" link=true></rtm-header> 
    <rtm-nav from="$ctrl.dataa.from", to="$ctrl.dataa.to", submit="console.log('xxx')">         
    </rtm-nav> 
    <div id="chart" class="demand-chart">
    </div>
</div>

运行应用程序时,dataa.fromdataa.to的文本输入会填充我引入的硬编码数据(10/01/201710/03/2017)。

问题在于“应用/提交”按钮。当我点击它时,我希望在控制台中看到消息(xxx),但没有任何反应。

现在它写为submit="console.log('xxx')",但我也尝试function{submit="console.log('xxx')};",导致以下错误:

  

standalone.js:16错误:[$ parse:syntax]语法错误:令牌'{'是一个   表达式第9列的意外标记   [function {console.log('xxx')]从[{console.log('xxx')]开始。

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

你不能在模板中使用像console.log()这样的函数,在控制器中声明一些东西并调用它:

而不是

<rtm-nav from="$ctrl.dataa.from", to="$ctrl.dataa.to", submit="console.log('xxx')">

DO

<rtm-nav from="$ctrl.dataa.from", to="$ctrl.dataa.to", submit="$ctrl.logSomething()">

并在控制器(视图)中声明它:

class DemandCtrl {
    constructor(ChartDataService) {
        this.ChartDataService = ChartDataService;
        debugger;
        this.dataa = {
            from: '10/01/2017',
            to:  '10/03/2017'
        };
        this.submit = () => {
            console.log('tesst');
        };
    }

    $onInit() {
        getData.call(null, this);       
    }

    logSomething() {
        console.log('www');
    }
}