我在基于angularjs的应用程序中有一个Html页面, 我想从页面中提取数据(例如,从日期和到目前为止),然后将此数据传递到控制器。 我想在一个对象中传递它。
例如:
<button ng-click="myControllerFunc(myObject)" />
如何创建此myobject并将其传递给myControlerFunc?
答案 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
};
为了完整起见,如果你提前定义事物,这里是控制器的主体。
$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在控制器内设置相同的变量。