Angular js 从默认值初始化 ng-model [英] Angular js init ng-model from default values

查看:24
本文介绍了Angular js 从默认值初始化 ng-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个表单,其中包含从数据库加载的值.你如何初始化 ng-model?

Say you have a form that has values loaded from database. How do you initialize ng-model?

示例:

<input name="card[description]" ng-model="card.description" value="Visa-4242">

在我的控制器中,$scope.card 最初是未定义的.除了做这样的事情,还有什么办法吗?

In my controller, $scope.card is undefined initially. Is there a way besides doing something like this?

$scope.card = {
  description: $('myinput').val()
}

推荐答案

这是新 Angular 应用程序中的常见错误.如果可以避免,您不想将值写入服务器上的 HTML 中.事实上,如果您可以避免让服务器完全渲染 HTML,那就更好了.

This is a common mistake in new Angular applications. You don't want to write your values into your HTML on the server if you can avoid it. If fact, if you can get away from having your server render HTML entirely, all the better.

理想情况下,您希望发送 Angular HTML 模板,然后通过 JSON 中的 $http 提取您的值并将它们放入您的作用域中.

Ideally, you want to send out your Angular HTML templates, then pull down your values via $http in JSON and put them in your scope.

因此,如果可能,请执行以下操作:

So if at all possible, do this:

app.controller('MyController', function($scope, $http) {
    $http.get('/getCardInfo.php', function(data) {
       $scope.card = data;
    });
});

<input type="text" ng-model="card.description" />

如果您绝对必须将您的值从您的服务器呈现到您的 HTML 中,您可以将它们放在一个全局变量中并使用 $window 访问它们:

If you absolutely MUST render your values into your HTML from your server, you could put them in a global variable and access them with $window:

在您的页面标题中,您要写出:

In the header of your page you'd write out:

<head>
   <script>
       window.card = { description: 'foo' };
   </script>
</head>

然后在你的控制器中你会得到它:

And then in your controller you'd get it like so:

app.controller('MyController', function($scope, $window) {
   $scope.card = $window.card;
});

希望能帮到你.

这篇关于Angular js 从默认值初始化 ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆