gpt4 book ai didi

html - 如何在页面加载时将 HTML 中的初始值获取到 Angularjs 中的 Controller

转载 作者:行者123 更新时间:2023-11-28 05:26:00 24 4
gpt4 key购买 nike

<ul>                                                                
<li ng-init="formData.mdpSunday='5'">
<input ng-model="formData.mdpSunday" name="mdpSunday" type="radio" value="5">
</li>
</ul>


app.controller('doublePointCtrl', function ($rootScope, $scope, $http, $filter, Flash) {
var data =$scope.formData.mdpSunday;
});

我无法在页面加载时获取 Controller 中的初始值

最佳答案

您想在 Angular 设置值之前读取 ngInit 值。

第一个选项:

因此您可以监听您的ngInit 值,并在她被设置时读取您的数据。您可以使用 $watch 方法:

Controller

(function(){

function Controller($scope) {

//Watch you ngInit value
$scope.$watch('data', function(){
//When your value is set, you can retrieve it
console.log($scope.data);
});


}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

HTML

  <body ng-app='app' ng-controller="ctrl" ng-init="data='5'">

<input type="text" ng-model="data">

</body>

但是,您不必使用 $watch。您可以获得更有效和更适当的方法来实现这一目标。

第二个选项:

您可以将 ngInit 设置为一个函数

Controller

(function(){

function Controller($scope) {

$scope.init = function(n){
$scope.data = n;
}


}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

HTML

  <body ng-app='app' ng-controller="ctrl" ng-init="init(5)">

<input type="text" ng-model="data">

</body>

我认为第二个选项更简洁。

关于html - 如何在页面加载时将 HTML 中的初始值获取到 Angularjs 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32306766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com