angularjs,uirouter - 在控制器更新时更新 ng-model?

angularjs, uirouter - Update ng-model on controller update?

视图 1:

<div ng-controller="ctrl1">
    <button ng-click="goToForm ({'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.

改变了视图

你做错了,你在改变 state 所以你必须传递数据,否则你会丢失它。

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

并在 ctrl1.js 中放置一个 init 函数,它检查是否有任何值作为 $stateParam 传递。如果有的话,相应分配。

app.controller('ctrl1',function($stateParams){

init(); // your first line of controller

// then all your code from here

function init(){
   if($stateParams.name) {
        $scope.selectedList.name = $stateParams.name;
    }
 }

})

您可以在 <div ng-init="init()">

上使用 ng-init="init()"

As per your code, wrap the default variable initialization in a method and call in ng-init of view1, ignore the view2 ng-init

Your controller should look as below

 $scope.initializeVariables=function(){
               $scope.selectedList= {name : ""} 
        }

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

And view1 should include ng-init directive as below

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