angularjs - 从控制器更新ng-model值?

时间:2018-05-15 09:57:36

标签: angularjs

查看1:

<div ng-controller="ctrl1">
    <button ng-click="goToExtendedForm({'name':'aaa'})">
    </button>
</div>

CTRL1:

    $scope.selectedList = {
        name: ""
    };

    $scope.goToForm = function(e) {
        $scope.selectedList.name = e.name;
        $state.go('view2');
        console.log(e); // prints updated value
    };

观看2:

<div ng-controller="ctrl1">

<input
        id="name"
        name="name"
        type="text"
        ng-model="selectedList.name"
        ng-readonly="true"
/>
</div>

但输入框始终为空,即使到达视图,也会调用goToForm()。为什么不更新HTML值? 使用ui.router的$ state更改视图。

3 个答案:

答案 0 :(得分:3)

根据您的描述,您的代码应该有效。检查是否将正确的参数传递给函数。这是一个有效的演示:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.selectedList = {
    name: ""
  };

  $scope.goToForm = function(e) {
    $scope.selectedList.name = e.name;
    console.log(e); // prints updated value
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  <button ng-click="goToForm({'name':'aaa'})">Change</button>
  <br>
  <input type="text" ng-model="selectedList.name" ng-readonly="true" />

</div>

答案 1 :(得分:0)

尝试在$scope.$apply()功能

的末尾添加$scope.goToForm

答案 2 :(得分:0)

试试这个;

HTML代码

  <div ng-app>
      <div ng-controller="ClickToEditCtrl">
        <input
                                id="name"
                                name="name"
                                type="text"
                                ng-model="selectedList.name"
                                ng-readonly="true"
                        />
                        <button ng-click="goToForm(testUserDetails)" >Go To</button>

                        </button>
      </div>
    </div>

像这样定义控制器;

function ClickToEditCtrl($scope) {
  $scope.selectedList = {
        name: ""
    };
$scope.testUserDetails ={
        name: "nimal"
}
    $scope.goToForm = function(e) {
        $scope.selectedList.name = e.name;
        console.log(e); // prints updated value
    };
}