Angularjs - 如何从不同的控制器提交表单?

时间:2016-11-09 10:43:49

标签: javascript angularjs forms angularjs-directive angularjs-scope

<div class="form-group">
    <label class="control-label" for="country">Country:<span>*</span></label>
    <select name="country" type="text" class="form-control" id="country">
        <option value="">--Country--</option>
        <?php
        include "../db/db.php"; //db-connection cause i want to load a country list
        $sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) { //check if an entry is there
            while($row = $result->fetch_assoc()) { //get the values from the db

                //now this is the part you have to implement in your script
                if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something

                    $optionSelected = "selected='selected'";

                } else{

                    $optionSelected = "";

                }

                //your foreache loop goes here / add the value that is selected here
                /*@foreach($categories as $category)
                        <option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
                @endforeach*/

                /**for my attempt it was this
                                {the id like as your category[id]}   {set the selected here inside the option tag}
                                                    ↓                  ↓                     */
                $countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
                echo $countrySet;
            }
        }
        $conn->close();
        ?>
    </select>
</div>

ctrl2 中,我想为 ctrl1

中的表单触发表单提交操作

如何在angularJs中实现这一目标?

3 个答案:

答案 0 :(得分:0)

您可以在按钮单击时发出一个事件,然后使用rootscope来向下广播 - 然后ctrl1可以听取这个提交表单作为回应。

答案 1 :(得分:0)

您可以从第二个控制器发出事件并在第一个控制器中收听它。

&#13;
&#13;
function CtrlOne($rootScope) 
{
  $rootScope.$on('submitEvent', function(event, args) {
      //submit your form here
  });
}

function CtrlTwo($scope,$rootScope) 
{
  $scope.submit=function(){
    $rootScope.$emit('submitEvent', args);
  }
}
&#13;
<div ng-controller="CtrlOne">
    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>
</div>

<div ng-controller="CtrlTwo">
    <button ng-click="submit()"> Submit </button>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用$rootScopeservicesevent brodcasting

来实现
app.controller('ctrl2',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.submitForm = $rootScope.mainSubmit();
}]);

app.run(function($rootScope){
    $rootScope.mainSubmit =function(){
        console.log("hey");
    };
})