如何从视图获取数据到控制器?

时间:2023-01-15 07:11:45

Inside my view I have declared a variable like this:

在我的视图中,我已经声明了一个这样的变量:

<span>{{myVariable = 25}}</span>

Now how do I obtain the value of myVariable in the controller?

那么如何在控制器中获取myVariable的值呢?

alert($scope.myVariable) is undefined.

警报(scope.myVariable美元)是未定义的。

I know this is quirky but just want to know how to declare variables in view and get the same in controller.

我知道这很奇怪,但只是想知道如何在视图中声明变量,并在控制器中得到相同的结果。

Any way I could do the same using ng-init ?

我可以用ng-init做同样的事情吗?

2 个解决方案

#1


1  

For the described scenario you could use ngInit However it would make more sense to initialize your variable in the controller if it is where you need it. This is is how you could do it from the view using ngInit:

对于描述的场景,您可以使用ngInit,但是如果您需要它的话,在控制器中初始化变量将更有意义。这就是如何使用ngInit从视图中实现的方法:

<span ng-init="myVariable = 25">{{myVariable }}</span>

https://docs.angularjs.org/api/ng/directive/ngInit

https://docs.angularjs.org/api/ng/directive/ngInit

#2


1  

You cant get the value from the controller in onload. But you can get like this (in onDemand)

在onload中无法从控制器获得值。但是你可以这样(在onDemand中)

$scope.click function() {
    alert($scope.myVariable)
}

#1


1  

For the described scenario you could use ngInit However it would make more sense to initialize your variable in the controller if it is where you need it. This is is how you could do it from the view using ngInit:

对于描述的场景,您可以使用ngInit,但是如果您需要它的话,在控制器中初始化变量将更有意义。这就是如何使用ngInit从视图中实现的方法:

<span ng-init="myVariable = 25">{{myVariable }}</span>

https://docs.angularjs.org/api/ng/directive/ngInit

https://docs.angularjs.org/api/ng/directive/ngInit

#2


1  

You cant get the value from the controller in onload. But you can get like this (in onDemand)

在onload中无法从控制器获得值。但是你可以这样(在onDemand中)

$scope.click function() {
    alert($scope.myVariable)
}