1. 程式人生 > >AngularJS 筆記二

AngularJS 筆記二

一切從模組化開始

// angular.module(name, [requires], [configFn]);

// name:字串型別,代表模組的名稱;
// requires:字串的陣列,代表該模組依賴的其他模組列表,如果不依賴其他模組,用空陣列即可;
var app = angular.module('app', ["ui.router"]);
// 路由:https://ui-router.github.io/ng1/docs/0.3.1/index.html#/api/ui.router
app.config(['$stateProvider','$urlRouterProvider', 
function
($stateProvider,$urlRouterProvider){
$stateProvider.state(stateName, stateConfig); //配置路由 //stateConfig預設包含的欄位: template, templateUrl, templateProvider, controller, controllerProvider, resolve, url, params, views, abstract, onEnter, onExit, reloadOnSearch, data $stateProvider.state('userInfo',{}); //配置路由
$urlRouterProvider.otherwise(defaultPath); //預設的路由 $urlRouterProvider.otherwise('/home.html'); }) $state.go('userInfo');
angular.bootstrap —–此方法用於手動載入angularjs模板
angular.bootstrap(element, [modules], [config]);
ng-app='main';
// 等同於
angular.bootstrap(document, ['main'])
data-ui-view 根據路由指定的url填充頁面
監聽頁面載入完畢
// 在controller裡面利用on或者watch
$scope.$on('$viewContentLoaded', function () {
     Metronic.initComponents();
});
localStorage 本地儲存
localStorage.setItem("MenuTree", angular.toJson(data));
localStorage.setItem("userInfo", angular.toJson($scope.userInfo));
localStorage.getItem("userInfo")
Angular的事件機制—$rootScope.$broadcast
app.controller('SomeCtrl', ['$rootScope', function($rootScope) {
    $rootScope.$broadcast("rootEvent", 'Data to Send');
    // $rootScope也可以通過$on訂閱從$rootScope.$broadcast釋出的事件
    $rootScope.$on("rootEvent", function(event, 'Data to Send') {
        // balabala
    });
}])
// 所有$scope都能夠通過$on訂閱從$rootScope.$broadcast釋出的事件
.controller('ParentCtrl', ['$scope', function($scope) {
    $scope.$on("rootEvent", function(event, 'Data to Send') {
        // balabala
    });
}])
.controller('SiblingOneCtrl', ['$scope', function($scope) {
    $scope.$on("rootEvent", function(event, 'Data to Send') {
        // balabala
    });
}])