以ng-click获取文本值

时间:2013-11-16 04:52:34

标签: javascript angularjs

Angular in Action开始练习,我正在尝试添加添加新“故事”的功能。

在下面的代码中,我试图通过添加stories数组来创建一个“newStory”,其中标题描述等于相关文本域中的当前文本。

app.html

    <div class="controls">
        <button id="addStory"
                    class="medium-btn"
                    type="button"
                ng-click="addNewStory(getNewStoryTitle(), getNewStoryDesc()">
    </button>

app.js

myModule.controller('MainCtrl', function($scope) { 
    $scope.newStoryTitle;
    $scope.newStoryDesc;

    $scope.getNewStoryTitle = function() { 
        return $scope.newStoryTitle;
    };

    $scope.getNewStoryDesc = function() { 
        return $scope.newStoryDesc;
    };

    $scope.stories = [
            {title: 'Story 00', description: 'Description pending.'},
                        ...
        ];

    $scope.createStory = function(t, d) { 
        const newStory = [{title: t, description: d}];
        $scope.stories = Array.prototype.concat($scope.stories, newStory);
    };

http://jsfiddle.net/S5ma7/

2 个答案:

答案 0 :(得分:3)

我已经更新了小提琴,主要是修复错误。方法是正确的,只需要一些小修复 - http://jsfiddle.net/S5ma7/7/

因为SO需要在此处粘贴代码:

var myModule = angular.module('Angello', []);

myModule.controller('MainCtrl', function ($scope) {
    $scope.currentStory = null;
    $scope.newStoryTitle = '';
    $scope.newStoryDesc = '';

    $scope.setCurrentStory = function (story) {
        $scope.currentStory = story;
    };

    $scope.getNewStoryTitle = function () {
        return $scope.newStoryTitle;
    };

    $scope.getNewStoryDesc = function () {
        return $scope.newStoryDesc;
    };

    $scope.stories = [{
        title: 'Story 00',
        description: 'Description pending.'
    }, {
        title: 'Story 01',
        description: 'Description pending.'
    }, {
        title: 'Story 02',
        description: 'Description pending.'
    }, {
        title: 'Story 03',
        description: 'Description pending.'
    }, {
        title: 'Story 04',
        description: 'Description pending.'
    }, {
        title: 'Story 05',
        description: 'Description pending.'
    }];

    $scope.addNewStory = function (t, d) {
        $scope.stories.push({
            title: t,
            description: d
        });
    };
});

答案 1 :(得分:1)

不知道这是否是演习的一部分,但可以更简单。

您可以使用ng-model属性声明模型,然后只需要一种方法将其添加到集合中。像这样:

 <form>
   <div>
     <label for="inputTitle">Title</label>
     <input type="text" id="inputTitle" placeholder="Title" ng-model="newStory.title">
   </div>
   <div>
     <label for="inputDescription">Description</label>
     <textarea id="inputDescription" placeholder="Description" rows="3" ng-model="newStory.description"></textarea>
   </div>
   <div>
     <button ng-click="addStory(newStory)">Add Story</button>
   </div>
  </form>

在你的控制器中:

$scope.stories = [];

$scope.addStory = function(story) {
    $scope.stories.push(story);
};

我希望这有帮助:http://jsfiddle.net/S5ma7/8/