在ui路由器中的状态之间共享ng模型数据

Sharing ng-model data between states in ui-router

本文关键字:共享 ng 模型 数据 之间 状态 ui 路由器      更新时间:2023-09-26

我似乎无法获得此表单来更新我的模型。它使用ng路由工作,但我决定改为ui路由器,因为我想嵌套模板。

我在这里尝试了一些事情。如何在angularjs-ui路由器中的状态之间共享$scope数据?但没有运气。

home.html

<form class="input-lg m-t m-l-n-xs hidden-lg hidden-md hidden-sm" role="search">
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-btn">
        <button type="submit" class="btn btn-sm bg-white btn-icon rounded"><i class="fa fa-search"></i></button>
      </span>
      <input type="text" ng-model="searchQuery" ng-change="changeView('search')" class="form-control input-sm no-border rounded" placeholder="Search songs, albums...">
    </div>
  </div>
</form>

控制器

  angular.module('musica', ['ui.bootstrap', 'ngFacebook', 'spotify', 'cb.x2js', 'ngRoute', 'ui.router'])
   .config(function ( $facebookProvider, SpotifyProvider, $routeProvider, $httpProvider, $stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/");
    $stateProvider
        .state('login', {
        url: "/",
            templateUrl: "partials/login.html",
        }).state('home', {
            templateUrl: "partials/home.html",
        }).state('home.select', {
        templateUrl: "partials/home.select.html"
        }).state('home.search', {
            templateUrl: "partials/home.search.html",
        }).state('home.queue', {
        templateUrl: "partials/home.queue.html"
        }).state('join', {
        templateUrl: "partials/join.html"
        }).state('creating', {
        templateUrl: "partials/creating_venue.html"
        }).state('home.server', {
        templateUrl: "partials/home.server.html"
        })
})
.controller( 'DemoCtrl', ['$scope','$rootScope', '$location', '$facebook', 'Spotify', 'x2js', '$http', '$state', 'globalStore', function ($scope, $rootScope, $location, $facebook, Spotify, x2js, $http, $state, globalStore) {
$scope.searchQuery='hello';
$scope.changeView = function(view){
        if(!$state.is('home.search'))
        {
            $state.go('home.search');
        } 
        $scope.searchTrack();
    };
$scope.searchTrack = function () {
    console.log('searching ' + $scope.searchQuery.query);
    Spotify.search(this.searchQuery.query, 'track').then(function (data) {
        $scope.tracks = data.tracks.items;
    });
};

如果我在搜索框中键入,我得到的只是hello,而不是更新后的值。我想,由于我在状态提供程序中没有提到控制器,所以只有一个控制器会被实例化。我真的很想知道发生了什么事。非常感谢。

$scope共享的一个想法是-我们需要reference,而不是valueType

因此,如果我们想在"家庭"层次结构家族之间共享数据。。。家庭控制器只需要引入Model = {}

.state('home', {
    templateUrl: "partials/home.html",
    controller: function($scope){ $scope.Model = {}},
    ...

稍后我们可以使用它来共享数据

$scope.Model.searchQuery = 'hello';

<input type="text" ng-model="Model.searchQuery" ...

还要检查:angularjs中模式窗口中的模型为空