Angular - 从控制器中的对象获取数据到ng-Model

时间:2016-01-21 10:44:16

标签: angularjs angularjs-scope angular-ui-router angular-ngmodel angularjs-ng-model

我无法从控制器中的对象将数据放入ng-model中。

VIEW1:

<input type="text" class="user-input" name="profile.firstname" ng-model="profile.firstname" ng-minlength="2" required pattern=".{2,}" placeholder="E.g. Anvika" title="Please enter atleast 2 characters">

当我单击VIEW2中的按钮时,它会触发一个函数(比如函数'test')。

视图2

<input type="submit" ng-click="register.test()" ui-sref="doctorRegister" value="Profile">

控制器:

var app = angular.module('app');
app.controller('registerController', ['$scope', 'tempDataStorageService', function ($scope, tempDataStorageService) {


var register = this;
register.doctor = {};
register.test = function () {
    register.refreshProfile = tempDataStorageService.get(register.doctor.profile);
    //console.log(register.refreshProfile);
    var a = register.refreshProfile.firstname;
    console.log(a);     
}
}

TempDataStorageService:

var app = angular.module('app'); 
app.factory('tempDataStorageService', function() {
    var savedData = {};
    function set(data) {
        savedData = data;
    }
    function get() {
        return savedData;
    }

    return {
        set: set,
        get: get
    }
});

编辑:我试图显示控制器的声明,如果这有帮助。 我怎样才能这样做,当我点击VIEW2上的Profile按钮时,它会用数据填充VIEW1?

1 个答案:

答案 0 :(得分:0)

the plunker:

Working example

html:

PriorityQueue::toString

JS:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl as mainCtrl">

    <form>
      <h2 class="text-primary">Get data into ng-Model from object in controller</h2>
      <hr>
      <div class="form-group">
        <h3 ng-class="!mainCtrl.firstName? 'text-danger' : 'text-success'">Enter Name</h3>
        <input type="text" class="form-control" ng-model="mainCtrl.firstName" placeholder="E.g. Anvika">
      </div>


      <hr>
      <h3 class="text-info">This is what you are typing: {{mainCtrl.firstName}}</h3>
      <button type="button" class="btn btn-success" ng-click="mainCtrl.test()">Save Name</button>
    </form>

    <hr>
    <h3 class="text-info">This is what is stored</h3>
    <h4>Doctor first name: {{mainCtrl.storedData.doctorFirstName}}</h4>
  </body>

</html>

<强>建议:

  1. 请在提问时正确格式化代码。
  2. 好的做法是使用风格指南。一个很好的起点是John Papa's Angular Style Guide