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

时间:2018-05-15 11:38:02

标签: angularjs angular-ui-router

查看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更改视图。

2 个答案:

答案 0 :(得分:1)

您做错了,您正在更改state,因此您必须传递数据,否则您将丢失它。

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

并在init中添加一个ctrl1.js函数,检查是否有任何值传递为$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;
    }
 }

})

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

答案 1 :(得分:0)

  

根据您的代码,将默认变量初始化包装在方法中   并调用view1的ng-init,忽略view2 ng-init

     

您的控制器应如下所示

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

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

并且view1应该包含ng-init指令,如下所示

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