访问pre填充输入字段控制器

访问pre填充输入字段控制器

本文介绍了访问pre填充输入字段控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是访问pre填充输入angularjs字段的值的最佳方式?例如,我怎么能访问控制范围之内(这是pre-填补页面加载)变量1的值?我使用的隐藏输入字段NG-模型指令,并使用$ scope.formData.variable1控制器,但没有运气访问。我试着在网上寻找类似的问题搜索,但大部分的例子均与上提交,或点击访问表单域。 是链接plnkr

 <机身NG控制器=MainController>
< H1> {{}信息}< / H1>
<表格名称=FORMDATA>  <输入类型=隐藏的名字=变量1NG模型=formdata.variable1VALUE =ABC/>
< /表及GT;

AngularJs code:

 (函数(){  VAR应用= angular.module(testapp,[]);  VAR MainController =功能($范围){
    的console.log($ scope.formData.variable1);    $ scope.message =你好,角!;
  };  app.controller(MainController,[$范围,MainController]);}());


解决方案

您可以做这样的事情。采用NG-INIT;

 <输入名称=数据[名]
       NG-模式=data.name
       NG-的init =data.name ='标志'/>

您可以使用指令。这样的事情。

 应用
.directive('ngDefaultValue',函数(){
  返回{
    限制:'A',
    控制器:函数($范围,$元,$ ATTRS,$​​解析){
        $解析($ attrs.ngModel).assign($范围,$ attrs.ngDefaultValue || $ attrs.value);
    }
  };
});

What is the best way to access pre-filled input fields values in angularjs? For example, how can I access the value of variable1 (which is pre-filled on pageload) within controller scope? I am using ng-model directive on the hidden input field and using $scope.formData.variable1 to access in the controller but with no luck. I tried searching in the web for similar issue, but most of the examples were related to accessing form field on submit or click. Here is link to plnkr

<body ng-controller="MainController">
<h1>{{message}}</h1>
<form name="formData">

  <input type="hidden" name="variable1" ng-model="formdata.variable1" value="abc" />
</form>

AngularJs Code:

(function() {

  var app = angular.module("testapp", []);

  var MainController = function($scope) {
    console.log($scope.formData.variable1);

    $scope.message = "Hello, Angular!";


  };

  app.controller("MainController", ["$scope", MainController]);

}());
解决方案

You can do something like this. using ng-init;

<input name="data[name]"
       ng-model="data.name"
       ng-init="data.name='mark'" />

or

You can use directive. something like this.

app
.directive('ngDefaultValue', function() {
  return {
    restrict: 'A',
    controller: function($scope, $element, $attrs, $parse) {
        $parse($attrs.ngModel).assign($scope, $attrs.ngDefaultValue || $attrs.value);
    }
  };
});

这篇关于访问pre填充输入字段控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:23