【问题标题】:AngularJS Trigger Function within another Controller另一个控制器中的 AngularJS 触发函数
【发布时间】:2015-12-28 06:26:36
【问题描述】:

我想要达到的目标:

  1. 在另一个控制器中获取/触发消息函数alertMessage();
  2. 使用 ID alertMessage(id:2); 选择要显示的特定消息。

当前问题:

  1. 无法从statsCtrl 控制器中获取或触发消息函数alertMessage();

  2. 除了使用var messageID = '1';之外,我无法通过警报功能指定消息ID,例如alertMessage(id:2);

我仍在学习 AngularJS,我知道我可能需要开发工厂或服务,但不知道这会变得多么棘手!

任何帮助和建议都会有所帮助!强>

控制器一:

fittingApp.controller('dashboardCtrl', ['$scope','$filter','$timeout','Notification','$sce','$mdDialog', function($scope,$filter,$timeout,Notification,$sce,$mdDialog) {
  // Dashboard > Username
  var username = 'Lucy'; // Test name
  $scope.username = username;

  // Dashboard > Alert Messages
  alertMessage();
  function alertMessage(){
    // Message ID
    var messageID = '1';
    // Messages
    var messages = {
      "results": [
        {'id':'1','icon':'','button':true,'title':'Welcome','subtitle':'Hi '+username+', welcome to the Virtual Fitting room','content': 'Here you will be able to browse through a selection of our dresses<br/>and shortlist them for future refrence. To help us find the best<br/>dress for you, please let us know a bit about yourself'},
        {'id':'2','icon':'','button':false,'title':'Raiding the Rails','subtitle':'','content': 'From the measurments you have supplied, we see you have a triangle body shape.<br/>Please wait while we get together the 5 best dresses for your shape.'},
        {'id':'3','icon':'','button':false,'title':'My Love List','subtitle':'','content': 'Any dresses you mark with a &#9829; will store<br/> into your Love list you can review at any<br/> point by clicking the heart icon.'},
        {'id':'4','icon':'','button':false,'title':'Show me the Style','subtitle':'','content': 'Feel free to look through the rest of our<br/> collection and &#9829; any that you like.'},
        {'id':'5','icon':'','button':false,'title':'Second Optionions','subtitle':'','content': 'It can be tough to choose, so why not ask<br/> the ones who know you best to help<br/>by voting for their favourites.'}
      ]
    };
    // Message Result
    var messageResult = $filter('filter')(messages.results,{id:messageID})[0];
    // Message HTML
    var message = '<h2>'+messageResult.title+'</h2><h3>'+messageResult.subtitle+'</h3><p>'+messageResult.content+'</p>';
    $scope.message = $sce.trustAsHtml(message);
    // Show Message
    $scope.showMessage = {
      active: true
    };
    // Hide Message
    $scope.hideMessage = function(){
      $scope.showMessage.active = !$scope.showMessage.active;
      // Trigger Notification
      notification();
    };
    // Hide 'Continue' Button
    $scope.hideButton = {
      active: true
    };
    if(messageResult.button === true){
      $scope.hideButton.active = !$scope.hideButton.active;
    }
  }

  // Dashboard > Notifications
  function notification(){
    // Bethan Test Notification
    $timeout(function(){
      Notification.bethan({
        message: 'Hi ' +username+ '! you’re not sure what to do? Hover the menu in the top right and click',
        positionY: 'bottom',
        positionX: 'left',
        delay: 10000,
        templateUrl: "views/notification.html"
      });
    }, 3000);
    // Rhiannon Test Notification
    $timeout(function(){
      Notification.rhiannon({
        message: 'This dress is perfect for a Triangle body shape like yours!',
        positionY: 'bottom',
        positionX: 'left',
        delay: null,
        templateUrl: "views/notification.html"
      });
    }, 6000);
  }
}]);

控制器二:

fittingApp.controller('statsCtrl', ['$scope', function($scope) {
  alertMessage();
}]);

完整的 JS

// START APP
var fittingApp = angular.module('fittingApp');

// Dashboard Controller
fittingApp.controller('dashboardCtrl', ['$scope','$filter','$timeout','Notification','$sce','$mdDialog','CustomService', function($scope,$filter,$timeout,Notification,$sce,$mdDialog,CustomService) {

    // Dashboard > Username
    var username = 'Lucy'; // Test name
    $scope.username = username;

    // Dashboard > Alert Messages
    alertMessage();
    function alertMessage(){
        // Message ID
        var messageID = '1';
        // Messages
        var messages = {
            "results": [
                {'id':'1','icon':'','button':true,'title':'Welcome','subtitle':'Hi '+username+', welcome to the Virtual Fitting room','content': 'Here you will be able to browse through a selection of our dresses<br/>and shortlist them for future refrence. To help us find the best<br/>dress for you, please let us know a bit about yourself'},
                {'id':'2','icon':'','button':false,'title':'Raiding the Rails','subtitle':'','content': 'From the measurments you have supplied, we see you have a triangle body shape.<br/>Please wait while we get together the 5 best dresses for your shape.'},
                {'id':'3','icon':'','button':false,'title':'My Love List','subtitle':'','content': 'Any dresses you mark with a &#9829; will store<br/> into your Love list you can review at any<br/> point by clicking the heart icon.'},
                {'id':'4','icon':'','button':false,'title':'Show me the Style','subtitle':'','content': 'Feel free to look through the rest of our<br/> collection and &#9829; any that you like.'},
                {'id':'5','icon':'','button':false,'title':'Second Optionions','subtitle':'','content': 'It can be tough to choose, so why not ask<br/> the ones who know you best to help<br/>by voting for their favourites.'}
            ]
        };
        // Message Result
        var messageResult = $filter('filter')(messages.results,{id:messageID})[0];
        // Message HTML
        var message = '<h2>'+messageResult.title+'</h2><h3>'+messageResult.subtitle+'</h3><p>'+messageResult.content+'</p>';
        $scope.message = $sce.trustAsHtml(message);
        // Show Message
        $scope.showMessage = {
        active: true
      };
        // Hide Message
        $scope.hideMessage = function(){
            $scope.showMessage.active = !$scope.showMessage.active;
            // Trigger Notification
            notification();
        };
        // Hide 'Continue' Button
        $scope.hideButton = {
            active: true
        };
        if(messageResult.button === true){
            $scope.hideButton.active = !$scope.hideButton.active;
        }
    }

    // Dashboard > Notifications
    function notification(){
        // Bethan Test Notification
        $timeout(function(){
            Notification.bethan({
                message: 'Hi ' +username+ '! you’re not sure what to do? Hover the menu in the top right and click',
                positionY: 'bottom',
                positionX: 'left',
                delay: 10000,
                templateUrl: "views/notification.html"
            });
        }, 3000);
        // Rhiannon Test Notification
        $timeout(function(){
            Notification.rhiannon({
                message: 'This dress is perfect for a Triangle body shape like yours!',
                positionY: 'bottom',
                positionX: 'left',
                delay: null,
                templateUrl: "views/notification.html"
            });
        }, 6000);
    }

    // Dashboard > Menu (FAB Speed Dial)
    menu();
    function menu(){
        $scope.hidden = false;
        // Menu Items
        $scope.items = [
            {name:"Help",icon:"svg/help.svg",direction:"left",backgroundColor:"rgb(239, 149, 73)"},
            {name:"Book",icon:"svg/book.svg",direction:"left",backgroundColor:"rgb(95, 205, 155)"},
            {name:"Contact",icon:"svg/contact.svg",direction:"left",backgroundColor:"rgb(32, 133, 188)"},
            {name:"Share",icon:"svg/share.svg",direction:"left",backgroundColor:"rgb(102, 181, 215)"},
            {name:"Exit",icon:"svg/exit.svg",direction:"left",backgroundColor:"rgb(255, 206, 97)"}
        ];
    }

    // Example
    $scope.$watchCollection(function() { return CustomService.showMsg; }, function(o, n){
        if(n === true){
            showMessage("Success");
        }
    });
    var showMessage = function(msg){
        alert(msg);
        CustomService.showMsg = false;
    };
    // END Example

}]);
// End Dashboard Controller

// Stats Controller
fittingApp.controller('statsCtrl', ['$scope', 'CustomService', function($scope, CustomService) {

    // Example
    $scope.clickMe = function(){
        console.log("Set true");
        CustomService.showMsg = true;
    };
    // END Example

    // Default Stats (Average UK Woman)
    defaultStats();
    function defaultStats(){
        $scope.height = 525; // 5'3"
        $scope.chest = 32; // 32"
        $scope.waist = 30; // 30"
        $scope.hips = 34; // 34"
        $scope.thighs = 20; // 20"
    }

    // Reset Stats
    $scope.resetStats = function(){
        defaultStats();
    };

    // Body Type Formula
    bodyShape();
    function bodyShape(){
        var bust = 32;
        var waist = 30;
        var hips = 34;
      var bustMeasure   = "";
        var waistMeasure  = "";
        var hipsMeasure   = "";
        var small   = "small";
        var medium  = "medium";
        var large   = "large";
        var shapeType = "";
        if ( bust <= 36 ) { bustMeasure = small;  }
        if ( bust <= 44 ) { bustMeasure = medium; }
        if ( bust >= 45 ) { bustMeasure = large;  }
        if ( waist <= 34 ) { waistMeasure = small;  }
        if ( waist <= 41 ) { waistMeasure = medium; }
        if ( waist >= 42 ) { waistMeasure = large;  }
        if ( hips <= 39 ) { hipsMeasure = small;  }
        if ( hips <= 47 ) { hipsMeasure = medium; }
        if ( hips >= 48 ) { hipsMeasure = large;  }
      var highestValue = Math.max(bust, waist, hips);
      var lowestValue = Math.min(bust, waist, hips);
      var difference = highestValue - lowestValue;
      if ( difference <= 5 ){
        shapeType = "Rectangle";
      }
      if (waist - bust > 5 && hips - bust > 5) {
          shapeType = "Triangle";
      }
      if (bust - waist > 5 && hips - waist > 5) {
          shapeType = "Hourglass";
      }
      if (waist - bust > 5 && waist - hips > 5) {
          shapeType = "Inverted Triangle";
      }
      if (hips - waist > 5 && hips - bust > 5) {
          shapeType = "Triangle";
      }
      if (bust - hips > (hips / 20)) {
          shapeType = "Inverted Triangle";
      }
      if ((bust - hips <= ( hips / 20)) && (waist > (bust * '.75'))) {
          shapeType = "Rectangle";
      }
      if (hips - bust > (bust/20)) {
         shapeType = "Triangle";
      }
      if ((waist <= (bust * '.75') && waist <= (hips * '.75'))) {
         shapeType = "Hourglass";
      }
        $scope.shapeType = shapeType;
    }
}]);
// End Stats Controller
// END APP

【问题讨论】:

  • then end of my answer 解释了如何创建自定义事件聚合器,这是您在此实例中所需要的
  • @CallumLinington 我不知道从哪里开始!您是否有任何进一步的建议、提示或我可以剖析的工作示例? Plnkr 会帮助您解决我的问题吗?
  • 是的,plnker 会有所帮助

标签: jquery angularjs angularjs-service angularjs-factory


【解决方案1】:

这是一种使用工厂从另一个控制器调用控制器功能的方法。

Demo

$scope.$watchCollection(function() { return CustomService; }, function(o, n){
    if(n.showMsg === true){
      showMessage("Success");
    }
});

【讨论】:

  • 我已尝试实现演示,我可以看到“设置为真”console.log,但点击时未触发警报!我已经通过上面的代码进行了更新,所以你可以看到我的整个 JS,以防万一我有一些冲突!
  • 您确定警报不起作用吗?因为我的它可以工作postimg.org/image/5srh7p4zx
  • 抱歉,您误会了,我的意思是警报没有显示在我的版本上。如果您想查看我的代码,我已经重新更新了我的 Git。
  • 如果这不起作用尝试 $broadcast docs.angularjs.org/api/ng/type/$rootScope.Scope
  • 又花了几个小时研究这个问题,但我仍然无法让它工作,您是否建议我重新开发消息传递功能以以某种方式在控制器外部工作?我愿意接受进一步的建议和建议!!!
猜你喜欢
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
相关资源
最近更新 更多