【问题标题】:How to call function in controller from another controller?如何从另一个控制器调用控制器中的函数?
【发布时间】:2016-07-12 04:48:23
【问题描述】:

我有 3 个 html 页面。 index.html、search-movie.html 和 result-movie html。我是

使用 ui-router 重定向页面。

search-movie.html 代码如下:

我在 html 页面中有文本和按钮。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Search Movie</title>
</head>
<body>
    <div class="bs-component" ng-controller="searchMovieController">
        <form class="well form-search">
            <fieldset>
                <legend>Search Movie</legend>
            </fieldset>
            <div>
                <label class="control-label" for="movie-name">Movie Name : </label>
                <input type="text" id="movie-name" class="input-small" style="margin-left: 10px;" placeholder="Please write movie name" ng-model="searchMovie">

                <a ui-sref="/result-movie" class="btn-sm btn-primary" style="margin-left: 10px;" ng-click="searchMovieF()">
                    <span class="glyphicon glyphicon-search"> Search</span>
                </a>
            </div>
        </form>
        <ul>
            <li> <h2>Title: {{name}}</h2></li>
            <li><h3>Release Date: {{release}}</h3></li>
            <li><h3>Length: {{length}}</h3></li>
            <li><h3>Description: {{description}}</h3></li>
            <li><h3>IMDb Rating: {{rating}}</h3></li>
        </ul>
    </div>            
</body>
</html>

这是我的 result-movie.html 代码,如下所示:

 <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Result Movie</title>
</head>
<body>
    <div id="forResult" class="bs-component" ng-controller="resultMovieController">
        <form class="well form-search" id="formResult">
            <fieldset>
                <legend>Result for Search Movie</legend>
            </fieldset>
        </form>
        <ul>
            <li> <h2>Title: {{name}}</h2></li>
            <li><h3>Release Date: {{release}}</h3></li>
            <li><h3>Length: {{length}}</h3></li>
            <li><h3>Description:{{description}}</h3></li>
            <li><h3>IMDb Rating: {{rating}}</h3></li>
        </ul>
        <a ui-sref="/search-movie" class="btn-sm btn-primary" style="margin-left:20px;">
            <span class="glyphicon glyphicon-circle-arrow-left">Back to Search Page</span>
        </a>
    </div>              
</body>
</html>

添加我的 app.js 如下:

(function (angular) {
    'use strict';

    var app = angular.module('adphorusWork', ['ui.router']);

    app.config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('/', {
            url: '/',
            templateUrl: 'welcome.html'
        })
        .state('/search-movie', {
                url: '/search-movie',
                templateUrl: 'search-movie.html',
                controller: 'searchMovieController'
        })
        .state('/result-movie', {
               url: '/result-movie',
               templateUrl: 'result-movie.html',
               controller: 'resultMovieController'
        });
        $urlRouterProvider.otherwise('/search-movie');
    });

     // I have no idea hoe can I use ? (with function)
    //app.factory('omdbService', function () {
    //    return {
    //        omdbData: {

    //        }
    //    };
    //});

    app.controller('searchMovieController', function ($scope, $http) {
        $scope.searchMovieF = function () {
            if ($scope.searchMovie.length > 0) {
                $scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json';
                $http.get($scope.api)
               .success(function (data) {
                   $("#movie-name").autocomplete({
                       source: data.Title
                   });
                   if ((data.Error != "Movie not found!") && ( data.Error != "Must provide more than one character.")) {
                       $scope.name = data.Title;
                       $scope.release = data.Released;
                       $scope.length = data.Runtime;
                       $scope.description = data.Plot;
                       $scope.rating = data.imdbRating;
                   }
                   else {
                       alert("Movie not found !")
                   }
               });
            } else {
                alert("Please write somethings !")
            }
        }
    });
    app.controller('resultMovieController', function ($scope) {
    });
})(angular);

我想要这个:当我将值写入文本(例如“游戏”)并单击时

按钮(在 search-movie.html 中),我应该在

中显示结果(例如 imdb、title 等)

结果-movie.html。我使用了 ui-router 并且正在工作,但我无法在 result-movie.html 中显示值。我可以在搜索页面中显示值,但我不想这样做。

一个控制器可以调用另一个控制器吗,或者我如何使用 .factory('servicethingss..')

【问题讨论】:

    标签: javascript html angularjs controller angularjs-scope


    【解决方案1】:

    将结果保存到 factory 并在另一个 controller 中使用它

    工作FIDDLE

    app.controller('searchMovieController', function ($scope, $http, resultFactory) {
            $scope.searchMovieF = function () {
                if ($scope.searchMovie.length > 0) {
                    $scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json';
                    $http.get($scope.api)
                   .success(function (data) {
                       $("#movie-name").autocomplete({
                           source: data.Title
                       });
                       if ((data.Error != "Movie not found!") && ( data.Error != "Must provide more than one character.")) {
                           var details = {
                               name:data.Title,
                               release: data.Released,
                               length: data.Runtime,
                               description: data.Plot,
                               rating: data.imdbRating
                           }
                           resultFactory.set(details)
    
                       }
                       else {
                           alert("Movie not found !")
                       }
                   });
                } else {
                    alert("Please write somethings !")
                }
            }
        });
        app.controller('resultMovieController', function ($scope,resultFactory) {
            $scope.result = function() {
                return resultFactory.details
            }
        });
    
    
        app.factory('resultFactory', function() {
            var details;
            var set = function(obj) {
                detail = obj
            }
            return {
                details: details,
                set: set
            }
        })
    

    【讨论】:

    • @eagle,也改变你的 resulthtml 页面,而不是 {{name}}{{result().name}} 如果它没有帮助,请给我 jsfiddle 来显示你的问题
    • 我已经添加了 JSFiddle,请检查它应该如何工作
    【解决方案2】:

    看看$rootScope.$broadcast$rootScope.$on

    $broadcast 创建一个“事件”,“on”是一个事件的监听器。因为它在 rootscope 上可以在控制器上运行。

    这解释得很好并且有示例代码:

    https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多