简体   繁体   中英

Accessing pre-filled input fields in controllers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM