【问题标题】:how to pass value from one view to another view in angular js?如何在角度js中将值从一个视图传递到另一个视图?
【发布时间】:2016-10-21 07:19:28
【问题描述】:

我想将我的第一个视图文本框值传递给另一个视图文本框。 并且这两个视图都使用不同的控制器。

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
</head>
<body>
    <div ng-view="">

    </div>
</body>
</html>


<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/angular-route.min.js"></script>
<script src="../Scripts/routeApp.js"></script>
<script src="../Scripts/Controller.js"></script>

这是我将加载 View1 和 view2 HTML 文件的主页。

“视图1”

<div>
    <input type="text" name="fname" value="" ng-model="fname" />
    <a href="#/View2" >Link</a>
</div>

“视图2”

<div>
    <input type="text" name="fname" value="" ng-model="fname" />
</div>

“routeApp.js”

var myApp = angular.module('myApp', ['ngRoute', 'yourApp']);
debugger
myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when('/',
    {
        templateUrl: 'View1.html',
        controller: 'View1'
    }).
    when('/View2',
    {
        templateUrl: 'View2.html',
        controller: 'View2'
    }).
    otherwise(
    {
        redirectTo: '/'
    });
}]);

“控制器.js”

var yourApp = angular.module("yourApp",[]);

yourApp.controller("View1", function ($rootScope, $scope) {
    debugger;
    $rootScope.abc = $scope.fname;
});

yourApp.controller("View2", function ($rootScope, $scope) {
    debugger;
    $scope.fname = $rootScope.abc;
});

我的电话是打给控制器的,但我知道我做错了,因为我没有在 View2.html 页面上获得我的价值。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    “Controlle.js”的变化,现在它对我来说工作正常......

    var yourApp = angular.module("yourApp",[]);
    
    yourApp.controller("View1", function ($rootScope, $scope, $window) {
        debugger;
        $rootScope.abc = $scope.fname;
    
        $scope.shareData = function () {
            debugger;
            $rootScope.abc = $scope.fname;
            $window.location.href = "#/View2";
        }
    });
    
    yourApp.controller("View2", function ($rootScope, $scope, $window) {
        debugger;
        $scope.fname = $rootScope.abc;
    });
    

    【讨论】:

      【解决方案2】:

      在分配$rootScope.abc = $scope.fname时,$scope.fname的值为undefined。您需要在更改状态之前保存该值。您可以使用 $destroy 事件来实现它:

      $scope.$on("$destroy", function(){
         $rootScope.abc = $scope.fname;
      });
      

      Click here to view in Plunker

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多