亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在AngularJS控制器之間共享數據

在AngularJS控制器之間共享數據

一只甜甜圈 2019-05-25 15:09:39
在AngularJS控制器之間共享數據我正在嘗試跨控制器共享數據。用例是一種多步形式,在一個輸入中輸入的數據稍后用于原始控制器外的多個顯示位置。下面的代碼和jsfiddle這里。HTML<div ng-controller="FirstCtrl">     <input type="text" ng-model="FirstName"><!-- Input entered here -->     <br>Input is : <strong>{{FirstName}}</strong><!-- Successfully updates here --></div><hr><div ng-controller="SecondCtrl">     Input should also be here: {{FirstName}}<!-- How do I automatically updated it here? --></div>JS// declare the app with no dependenciesvar myApp = angular.module('myApp', []); // make a factory to share data between controllersmyApp.factory('Data', function(){     // I know this doesn't work, but what will?     var FirstName = '';     return FirstName;});// Step 1 ControllermyApp.controller('FirstCtrl', function( $scope, Data ){});     // Step 2 ControllermyApp.controller('SecondCtrl', function( $scope, Data ){     $scope.FirstName = Data.FirstName;});任何幫助是極大的贊賞。
查看完整描述

4 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

我不喜歡$watch這樣做。您可以只分配數據,而不是將整個服務分配給控制器的范圍。

JS:

var myApp = angular.module('myApp', []);myApp.factory('MyService', function(){
  return {
    data: {
      firstName: '',
      lastName: ''
    }
    // Other methods or objects can go here
  };});myApp.controller('FirstCtrl', function($scope, MyService){
  $scope.data = MyService.data;});myApp.controller('SecondCtrl', function($scope, MyService){
   $scope.data = MyService.data;});

HTML:

<div ng-controller="FirstCtrl">
  <input type="text" ng-model="data.firstName">
  <br>Input is : <strong>{{data.firstName}}</strong></div><hr><div ng-controller="SecondCtrl">
  Input should also be here: {{data.firstName}}</div>

或者,您可以使用直接方法更新服務數據。

JS:

// A new factory with an update methodmyApp.factory('MyService', function(){
  return {
    data: {
      firstName: '',
      lastName: ''
    },
    update: function(first, last) {
      // Improve this method as needed
      this.data.firstName = first;
      this.data.lastName = last;
    }
  };});// Your controller can use the service's update methodmyApp.controller('SecondCtrl', function($scope, MyService){
   $scope.data = MyService.data;

   $scope.updateData = function(first, last) {
     MyService.update(first, last);
   }});


查看完整回答
反對 回復 2019-05-25
  • 4 回答
  • 0 關注
  • 732 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號