角JS初始化从默认值NG-模型 [英] Angular js init ng-model from default values

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

问题描述

假设你有一个具有从数据库加载值的表格。你如何初始化NG-模式?

例如:

 <输入名称=牌[说明]NG模型=card.descriptionVALUE =签证-4242>

在我的控制器,$ scope.card最初是不确定的。是否有除了做这样的事情的一种方式?

  $ scope.card = {
  说明:$('myinput')VAL()。
}


解决方案

这是在新的角度应用中常见的错误。你不想你的价值观写入服务器上的HTML,如果你能避免它。如果事实上,如果你可以从让你的服务器渲染HTML完全脱身,就更好了。

在理想情况下,你想送你的角HTML模板,然后通过HTTP $ JSON中拉下你的价值观,并把它们在你的范围。

因此​​,如果可能的话,做到这一点:

  app.controller('myController的',函数($范围,$ HTTP){
    $ http.get('/ getCardInfo.php'功能(数据){
       $ scope.card =数据;
    });
});<输入类型=文本NG模型=card.description/>

如果你绝对必须使你的价值观到HTML从你的服务器,你可以把它们放在一个全局变量和$窗口访问它们:

在你的页面标题你会写出来:

 < HEAD>
   <脚本>
       window.card = {说明:'富'};
   < / SCRIPT>
< /头>

然后在你的控制器,你会得到它像这样:

  app.controller('myController的',函数($范围,$窗口){
   $ scope.card = $ window.card;
});

我希望帮助。

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

Example:

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

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

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

解决方案

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.

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" />

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;
});

I hope that helps.

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

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