angularjs-杂项

Sublime 代码编辑工具
Webstorm 代码编辑工具 file setring 设置插件
Chrome 浏览器 Batarang调试工具
Github gitTortoise图形化界面
Grunt Js文件合并、代码压缩,Ctrl+s 自动执行,Ctrl+s集成测试
Nodejs
Karma 单元测试 Jasmime单元测试

一、$http 服务使用

var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http',
    function($http) {
        var doRequest = function(username, path) {
            return $http({
                method: 'GET',
                url: 'users.json'
            });
        }
        return {
            userList: function(username) {
                return doRequest(username, 'userList');
            }
        };
    }
]);
//自己定义的service放在最后
myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
    function($scope, $timeout, userListService) {
        var timeout;
        $scope.$watch('username', function(newUserName) {//监控前台数据变化
            if (newUserName) {
                if (timeout) {
                    $timeout.cancel(timeout);
                }
                timeout = $timeout(function() {
                    userListService.userList(newUserName)
                        .success(function(data, status) {
                            $scope.users = data;
                        });
                }, 350);
            }
        });
    }
]);

二、Filter实现

myModule.filter('filter1',function(){
    return function(item){
        return item + 'o()o';
    }
});  
   {{'大漠穷秋'|filter1 }}

第二章 代码总结
var bookStoreApp = angular.module('bookStoreApp', [
    'ngRoute', 'ngAnimate', 'bookStoreCtrls', 'bookStoreFilters',
    'bookStoreServices', 'bookStoreDirectives'
]);

bookStoreApp.config(function($routeProvider) {
    $routeProvider.when('/hello', {
        templateUrl: 'tpls/hello.html',
        controller: 'HelloCtrl'
    }).when('/list', {
        templateUrl: 'tpls/bookList.html',
        controller: 'BookListCtrl'
    }).otherwise({
        redirectTo: '/hello'
    })
});

一、Directive示例
1.Link函数和scope

var app=angular.module("helloWordApp",[]);
app.controller('MainCtrl',function($scope){
    $scope.color="red";
});
app.directive("helloWord",function(){
    return {
        restrict:'AE',//A属性E元素template替换,Cclass,默认A
        replace:true,//替换掉自己的标签
     template:'

hellorWord

', //link函数主要用来为DOM元素添加事件监听、监视模型属性变化、以及更新DOM link: function(scope,elem,attrs ){ //scope就是父controller的scope。 elem.bind('click',function(){ elem.css('background-color','white'); scope.$apply(function(){ scope.color="white"; }); }); elem.bind('mouseover',function(){ elem.css('cursor','pointer'); }); } }; });

2.Compile
compile 函数在 link 函数被执行之前用来做一些DOM改造。它接收下面的参数:
tElement – 指令所在的元素
attrs – 元素上赋予的参数的标准化列表
要注意的是 compile 函数不能访问 scope,并且必须返回一个 link 函数。

app.directive('test', function() {
    return {
        compile: function(tElem,attrs) {
            //do optional DOM transformation here
            return function(scope,elem,attrs) {
                //linking function here
            };
        }
    };
});

3.其他两种改变作用域的例子,默认false继承不隔离,true继承隔离{}隔离

app.directive('helloWorld', function() {
    return {
        scope: true,
// use a child scope that inherits from parent
        restrict: 'AE',
        replace: 'true',
        template: '

Hello World!!

' }; }); app.directive('helloWorld', function() { return { scope: {}, // use a new isolated scope,父作用域无法看到子作用域,完全隔离 restrict: 'AE', replace: 'true', template: '

Hello World!!

' }; });

4.例子

var expanderModule=angular.module('expanderModule', [])
expanderModule.directive('expander', function() {
    return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
            title : '=expanderTitle'
        },
        template : '
' + '
{{title}}
' + '
' + '
', link : function(scope, element, attrs) { scope.showMe = false; scope.toggle = function toggle() { scope.showMe = !scope.showMe; } } } }); expanderModule.controller('SomeController',function($scope) { $scope.title = '点击展开'; $scope.text = '这里是内部的内容。'; });

HTML代码:

    
{{text}}

5.Transclude指定替换的位置ng-transclude

var app = angular.module("app", [])
    .directive("hello", function () {
        var option = {
            restrict: "AECM",
            template: "

Hello, Directive,

", replace: true, transclude: true }; return option; }) 12345678 //替换为了

Hello, Directive, 12345678

6.Scope配合@,=,&数据绑定
(1)@单向绑定

var myApp=angular.module('myApp',[]);
myApp.controller('listCtrl',function($scope){
    $scope.logchore="motorola";
});
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            title:"@"
        },
        template:'
{{title}}
' } });
//这个必须指定的,这里的title是指令里scope的@对应的,t就是控制域scope下的 我的angularjs

(2)=双向绑定

    
//和上面相比,这个直接赋值等于scope域下的t了

{{title}}

我的angularjs
myApp.directive('kid',function(){ return { 'restrict':'E', scope:{ title:"=" }, template:'
{{title}}
' } });

(3)最后说&,这个是用来方法调用的

    
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            flavor:"&"
        },
        template:'
' } }); myApp.controller('listCtrl',function($scope){ $scope.logchore=function(x){ alert(x); }; });

7、Controller

//controller
appControllers.controller('mainCtrl', ['$scope',
  function($scope) {
    $scope.changedTime = function(time) {
      alert(time);
    }
  }]).directive('timePicker',['$http', function($http) {
  return {
    restrict: 'AE',
    templateUrl: 'partials/time-picker.html',
    scope: true,
    controller: 'TimepickerDemoCtrl'
  };
}]);


//partials/time-picker.html:

    
    
//TimepickerDemoCtrl (copy from source):
var TimepickerDemoCtrl = function ($scope) {
  $scope.mytime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 15;
  $scope.options = {
    hstep: [1, 2, 3],
    mstep: [1, 5, 10, 15, 25, 30]
  };
  $scope.ismeridian = true;
  $scope.toggleMode = function() {
    $scope.ismeridian = ! $scope.ismeridian;
  };
  $scope.update = function() {
    var d = new Date();
    d.setHours( 14 );
    d.setMinutes( 0 );
    $scope.mytime = d;
  };
  $scope.changed = function () {
    console.log('Time changed to: ' + $scope.mytime);
  };
}

8.一个重要的tab例子,涉及到controller作用域等


BootStrap Tab Component

This is the content of the first tab.
This is the content of the second tab.
angular.module('components', []). directive('tabs', function() { return { restrict: 'E', transclude: true, scope: {}, controller: [ "$scope", function($scope) { var panes = $scope.panes = []; $scope.select = function(pane) { angular.forEach(panes, function(pane) { pane.selected = false; }); pane.selected = true; } this.addPane = function(pane) { if (panes.length == 0) $scope.select(pane); panes.push(pane); } }], template: '
' + '' + '
', replace: true }; }). directive('pane', function() { return { require: '^tabs',//^在指令的上游查找控制器,?当前指令,没有前缀,自身所提供的控制器中查找;本例是吧tabs中的控制器传入 restrict: 'E', transclude: true, scope: { title: '@' }, link: function(scope, element, attrs, tabsCtrl) { tabsCtrl.addPane(scope); }, template: '
', replace: true }; })

二、Service示例
1.服务器请求http

angular.module('myApp.services', [])
    .factory('githubService', ['$http', function($http) {
      var githubUsername;
      var doRequest = function(path) {
        return $http({
          method: 'JSONP',
          url: 'https://api.github.com/users/' + githubUsername + '/' + path + '?callback=JSON_CALLBACK'
        });
      }
      return {
        events: function() { return doRequest('events'); },
        setUsername: function(newUsername) { githubUsername = newUsername; }
      };
    }]); 

2.一个音乐播放器服务

app.factory('player', ['audio', function(audio) {
  var player = {
    playing: false,
    current: null,
    ready: false,
    play: function(program) {
      // If we are playing, stop the current playback 
      if (player.playing) player.stop();
      var url = program.audio[0].format.mp4.$text; // from the npr API 
      player.current = program; // Store the current program 
      audio.src = url;
      audio.play(); // Start playback of the url 
      player.playing = true
    },
    stop: function() {
      if (player.playing) {
        audio.pause(); // stop playback 
        // Clear the state of the player 
        playerplayer.ready = player.playing = false;
        player.current = null;
      }
    }
  };
  audio.addEventListener('ended', function() {
    $rootScope.$apply(player.stop());
  }); 
  return player;
}]); 

二、Filter代码示例
3.简单示例

{{'大漠穷秋'|filter1 }}
myModule.filter('filter1',function(){
    return function(item){
        return item + 'o(∩_∩)o';
    }
});  

三、Http请求示例
1.后台请求数据

myModule.controller('LoadDataCtrl', ['$scope','$http', function($scope,$http){
   $http({
        method: 'GET',
        url: 'data.json'
    }).success(function(data, status, headers, config) {
        console.log("success...");
        console.log(data);
        $scope.users=data;
    }).error(function(data, status, headers, config) {
        console.log("error...");
    });
}]);
//前端
  • {{user.name}}

2.Service+后台请求数据

var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http',
    function($http) {
        var doRequest = function(username, path) {
            return $http({
                method: 'GET',
                url: 'users.json'
            });
        }
        return {
            userList: function(username) {
                return doRequest(username, 'userList');
            }
        };
    }
]);

myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
    function($scope, $timeout, userListService) {
        var timeout;
        $scope.$watch('username', function(newUserName) {
            if (newUserName) {
                if (timeout) {
                    $timeout.cancel(timeout);
                }
                timeout = $timeout(function() {
                    userListService.userList(newUserName)
                        .success(function(data, status) {
                            $scope.users = data;
                        });
                }, 350);
            }
        });
    }
]);
//前端
{{users}}

四、页面跳转传参

$routeProvider.when('/gerenxiangqing/:userId', {templateUrl: 'xiangqing/gerenxiangqing.html',controller:'GeRenXiangQing', reloadOnSearch: false});
ziYuan.controller('GeRenXiangQing',function($scope,httpService,$routeParams){
    $scope.guanzhuInfo="关注";//button 显示的信息
    $scope.id=$routeParams.userId;
    //判断是否关注,然后显示button信息
    httpService.events({id: $scope.id}, "userController/isGuanZhu")
               .success(function (data, status, headers, config) {
        if (data == 1) {//已关注
            $scope.guanzhuInfo = "已关注";
        } else if (data == 0) {//未关注
            $scope.guanzhuInfo = "关注";
        }
    }).error(function (data, status, headers, config) {
    });
 });

五、知识点
1.ng-repeat="message in messages track by $index"
$index $first $last
ng-class=”{‘selected’:true}”
2.ng-bing 等价于 {{}}
3.{{reverse()}} 方法可以直接调用
4.翻转字符串 msg.split(“”).reverse().jion(“”);
5.服务 value 可以改变,constant不可以变,factory比较常用,service
6..factory('githubService', ['$http', function($http) {
return {
msg:”fd”;
alertInfo:function(){alert(“fd”)}
}
};
}]);

service('githubService', ['$http', function($http) {
              return {
              msg:”fd”;
          alertInfo:function(){alert(“fd”)}
           }
      };
 }]); 
factory('githubService', ['$http', function($http) {
            return new dd();              
     };
 }]); 
//等价于
Function dd(){
    this.mgs=”fd”;
    this.alertInfo=function(){alert(“fd”)}
}

8.多个service共享数据,Data是个共享的容器,比如购物车的使用

你可能感兴趣的:(angularjs-杂项)