2017-06-19 92 views
0

我想知道是否有可能建立一个独立的指令。All In One指令+服务+控制器

我在AngularJS上非常新,请让我知道是否有我正在寻找的深层概念错误。

我目前的 “尝试” 是:

(function() { 
    // a module for holding the directive 
    var app = angular.module('monitorApp', []); 

    // a service for getting some data 
    app.service("MonitorService", function ($http, $q) { 
     return ({ 
      getMonitorInfo: getMonitorInfo 
     }); 

     function GetMonitorInfo() { 
      var request = $http({ 
       method: "get", 
       url: "/IndicatorsReport/GetMonitorInfo" 
      }); 
      return (request.then(notifyErrorIfNeed, handleError)); 
     } 

     function handleError(response) { 
      if (!angular.isObject(response.data) || !response.data.message) { 
       return ($q.reject("An unknown error occurred.")); 
      } 
      return ($q.reject(response.data.message)); 
     } 

     function notifyErrorIfNeed(response) { 
      var data = response.data; 
      if (data.status !== "success") { 
       new PNotify({ 
        title: data.title, 
        text: data.text, 
        type: 'error', 
        hide: false, 
        styling: 'bootstrap3' 
       }); 
      } 
      return data; 
     } 
    }); 

//我的实际指令

app.directive('monitorButton', function ($document) { 
     // a self initializing controller 
     var controller = ['$scope', function ($scope, MonitorService) { 
      var vm = this; 
      function init() { 
       MonitorService.GetMonitorInfo().then(function (data) { 
        // this is the actual data 
        vm.feedBots = data.feedBots; 

        // this is fake data yet 
        vm.flags = { 
         cls: 'bg-blue', 
         number: 3, 
         show: true 
        }; 
       }); 
      } 
      init(); 
     }]; 

     //a very simple template 
     var template = '<button type="button" class="btn btn-app">' + 
         ' <span class="badge {{vm.flags.cls}}" ng-show="vm.flags.show">{{vm.flags.number}}</span>'+ 
         ' <i class="fa fa-dashboard"></i> Monitor'+ 
         '</button>'; 

     // my directive params 
     return { 
      restrict: 'EA', 
      controller: controller, 
      scope: {}, 
      controllerAs: 'vm', 
      bindToController: true, 
      template: template 
     }; 
    }); 
}()); 

我打算只将以下代码添加到我的html页面(与angularjs沿偏离航向) :

<script src="/app/directives/monitor.js" type="text/javascript"></script> 

最后,我天真地打算把它想:

<monitor-button></monitor-button> 

编辑

它不工作,我没有看到网页中的任何元素。

+1

这是什么问题? – Phix

+0

所有看起来不错,你有任何控制台错误? – MarkoCen

+0

对不起:它没有工作,我没有看到页面中的任何元素。 –

回答

1

对于独立角应用程序,请angular.bootstrap来引导你的页面上的应用程序,

//monitor.js 
(function(){ 

    var app = angular.module('monitorApp', []); 

    //define your app... 

    //bootstrap your app... 
    angular.bootstrap(document, ['monitorApp']); 

})() 
+0

不错,非常感谢,我不知道:) –