假设您有一个从数据库加载值的表单.你如何初始化ng模型?
例:
<input name="card[description]" ng-model="card.description" value="Visa-4242">
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,$ scope.card最初是未定义的.除了做这样的事情之外还有办法吗?
$scope.card = {
description: $('myinput').val()
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*cok 236
如果您无法修改您的应用程序以执行@blesh建议(使用$ http或$ resource拉下JSON数据并填充$ scope),则可以使用ng-init代替:
<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">
Run Code Online (Sandbox Code Playgroud)
另请参阅AngularJS - 使用ng模型时,将忽略输入文本框中的Value属性?
Ben*_*esh 136
这是新Angular应用程序中的常见错误.如果可以避免,则不希望将值写入服务器上的HTML.事实上,如果你可以让你的服务器完全呈现HTML,那就更好了.
理想情况下,您希望发送Angular HTML模板,然后通过JSON中的$ http下拉您的值并将它们放在您的范围内.
所以如果可能的话,这样做:
app.controller('MyController', function($scope, $http) {
$http.get('/getCardInfo.php', function(data) {
$scope.card = data;
});
});
<input type="text" ng-model="card.description" />
Run Code Online (Sandbox Code Playgroud)
如果您绝对必须将您的值从服务器呈现到HTML中,您可以将它们放在全局变量中并使用$ window访问它们:
在你的页面标题中你写出来:
<head>
<script>
window.card = { description: 'foo' };
</script>
</head>
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器中,你会得到它:
app.controller('MyController', function($scope, $window) {
$scope.card = $window.card;
});
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助.
Kev*_*one 60
对于AngularJS来说,这显然是缺乏但很容易添加的修复.只需编写一个快速指令即可从输入字段设置模型值.
<input name="card[description]" value="Visa-4242" ng-model="card.description" ng-initial>
Run Code Online (Sandbox Code Playgroud)
这是我的版本:
var app = angular.module('forms', []);
app.directive('ngInitial', function() {
return {
restrict: 'A',
controller: [
'$scope', '$element', '$attrs', '$parse', function($scope, $element, $attrs, $parse) {
var getter, setter, val;
val = $attrs.ngInitial || $attrs.value;
getter = $parse($attrs.ngModel);
setter = getter.assign;
setter($scope, val);
}
]
};
});
Run Code Online (Sandbox Code Playgroud)
jto*_*mpl 12
恕我直言,最好的解决方案是@Kevin Stone指令,但我必须升级它才能在各种条件下工作(fe select,textarea),而且这个是有效的:
angular.module('app').directive('ngInitial', function($parse) {
return {
restrict: "A",
compile: function($element, $attrs) {
var initialValue = $attrs.value || $element.val();
return {
pre: function($scope, $element, $attrs) {
$parse($attrs.ngModel).assign($scope, initialValue);
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用自定义指令(支持textarea,select,radio和checkbox),查看此博客文章https://glaucocustodio.github.io/2014/10/20/init-ng-model-from-form- fields-attributes /.
您也可以在HTML代码中使用:
ng-init="card.description = 12345"
Angular不推荐使用,如上所述,您应该只使用您的控制器.
但它的工作原理:)
| 归档时间: |
|
| 查看次数: |
224037 次 |
| 最近记录: |