AngularJS:将对象参数从视图传递到控制器函数

时间:2014-07-22 09:29:53

标签: jquery angularjs model-view-controller

我在基于angularjs的应用程序中有一个Html页面, 我想从页面中提取数据(例如,从日期和到目前为止),然后将此数据传递到控制器。 我想在一个对象中传递它。

例如:

<button ng-click="myControllerFunc(myObject)" />

如何创建此myobject并将其传递给myControlerFunc?

4 个答案:

答案 0 :(得分:2)

如果您在对象上使用ng-repeat,您可以使用函数调用直接发送对象,例如: -

<div ng-repeat="item in items">
 <button data-ng-click="callFunction(item)">call my object</button>
</div>

...

在您的控制器中,您可以在功能中阅读

$scope.callFunction = function(item){
     console.log(item);
};

因此,您可以获得完整的数据。干杯!

答案 1 :(得分:0)

如果数据在范围内,然后你想在点击按钮时填充myObject,你可以在控制器中做这样的事情:

$scope.myControllerFunc =function(myObject) {
     myObject.fromDate = $scope.fromDate;
     myObject.toDate = $scope.toDate;
}

如果从html元素中获取数据,那么您可以使用angular.element并执行以下操作:

$scope.myControllerFunc =function(myObject) {
     var fromDate = angular.element( document.querySelector( '#fromDate' ) );
     var toDate= angular.element( document.querySelector( '#toDate' ) );
     myObject.fromDate = fromDate.val();
     myObject.toDate = toDate.val();
}

答案 2 :(得分:0)

您可以在myObject对象的控制器中提前定义对象(在您的示例中,我们将讨论$scope),并使用ng-model绑定字段到对象的属性。但是,您不必提前定义对象。 ngModel会在绑定时为您创建对象,如果可以的话。

  <form name="frm" ng-submit="myControllerFunc(myObject)">
    From date:
    <input type="date" ng-model="myObject.fromDate" />
    <br />To date:
    <input type="date" ng-model="myObject.toDate" />
    <br />
    <button type="submit">Submit</button>
    <small>Check console log for value upon submit</small>
  </form>

对于该函数,在控制器中的$scope对象上定义它。在这个例子中,传入对象是多余的,因为你可以在$scope而不是参数上引用它,但是你可能有你的理由。

$scope.myControllerFunc = function(obj) {
    console.log(obj); // do whatever you want with obj
};

Demo

为了完整起见,如果你提前定义事物,这里是控制器的主体。

$scope.myObject = { fromDate: null, toDate: null };

$scope.myControllerFunc = function() {
    console.log($scope.myObject); // do whatever you want with obj
};

除了您可以从ng-submit

中删除参数外,该视图不会有任何不同
<form name="frm" ng-submit="myControllerFunc()">

根据您的需要混合搭配。

此外,您不必使用ng-submit来调用我的示例中显示的功能(我没有看到包含此​​详细信息的编辑)。您可以按照myControllerFunc按钮ng-click,就像我在ng-submit中使用它一样。

答案 3 :(得分:0)

我认为你对角度如何工作有一点误解。您的页面在控制器内部的日期和日期将如下所示。

<div data-ng-controller="searchBar" data-ng-init="id='g3_v1'" class="widget">
    <form data-ng-submit="formSubmit()">
        From date: <input data-ng-model="fromDate" type="text" ><br/>
        To   date: <input data-ng-model="toDate" type="text" ><br/>
        <button ng-click="formSubmit()" />
    </form>
</div>

控制器代码如下:

$scope.formSubmit = function() {
    var data = {"toDate":$scope.toDate, 
                "fromDate": $scope.fromDate};
    $http({
        url: "json/search", 
        method: "GET",
        params: data
     }).then(
         function(resp)
         {
             //success callback
         },
         function(error)
         {
             //failure callback
     });
};

如果toDate和fromDate超出您的控制范围,您可以使用service在控制器内设置相同的变量。