简体   繁体   中英

How to add submit function to my ng-controller

I am trying to learn angular so forgive my stupid mistakes and ignorance. That being said, I add data to my scope when I create my controller ProducerCtrl. This works before I add anything else. When I add the addname function it breaks my data fetch. I am sure I am doing something wrong because I don't know what I am doing. I would like to have these two bits of code work. Maybe I need to move one or both to another area.

<html><head>
    <title></title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var eventApp = angular.module('eventApp', []);

var szAction = "/GoGetData";
var szAction2 = "/GoPostData" })";

eventApp.controller('ProducerCtrl', ['$scope', '$http', function (scope, http) {
    http.get(szAction).success(function (data) {
        scope.producer = data;
    });

    $scope.addName = function () {
        http.post(szAction2, scope.producer);

    };
}]);
</script>
</head>
<body>
<div ng-app="eventApp">
    <div ng-controller="ProducerCtrl">
        Name:<input ng-model="producer.Name" type="text" /><br>
        Hello {{producer.Name}}

        <form ng-submit="addName()">
            <input ng-model="producer.Name" type="text">
            <input type="submit" value="add">
        </form>
    </div>
</div>
</body></html>

I've made some changes on your code. When you click on add will prompt an alert.

Your HTML:

<body>
    <div ng-app="eventApp">
        <div ng-controller="ProducerCtrl">
            Name:<input ng-model="producer.Name" type="text" /><br />
            Hello {{producer.Name}}

            <form ng-submit="addName()">
                <input ng-model="producer.Name" type="text" />
                <input type="submit" value="add" />
            </form>
        </div>
    </div>
<body>

Your Angular code:

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

eventApp.controller('ProducerCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.producer = { Name : '' };

    $scope.addName = function () {
        alert($scope.producer.Name);
    };
}]);

See here .

Take a look here to check $http.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM