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';
    }
});  
<body>   {{'大漠穷秋'|filter1 }}
</body>
第二章 代码总结
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:'<p style="background-color:{{color}}">hellorWord</p>',
    //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');
            });
        }
    };
});
<div ng-controller="MainCtrl">
    <input type="text" ng-model="color"  placeholder="Enter aColor"/>
    <hello-word/>
</div>

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: '<h3>Hello World!!</h3>'
    };
});
app.directive('helloWorld', function() {
    return {
        scope: {},  // use a new isolated scope,父作用域无法看到子作用域,完全隔离
        restrict: 'AE',
        replace: 'true',
        template: '<h3>Hello World!!</h3>'
    };
});

4.例子

var expanderModule=angular.module('expanderModule', [])
expanderModule.directive('expander', function() {
    return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
            title : '=expanderTitle'
        },
        template : '<div>'
        + '<div class="title" ng-click="toggle()">{{title}}</div>'
        + '<div class="body" ng-show="showMe" ng-transclude></div>'
        + '</div>',
        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代码:

    <div ng-controller='SomeController'>
    <expander class='expander' expander-title='title'>
    {{text}}
</expander>
</div>

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

var app = angular.module("app", [])
    .directive("hello", function () {
        var option = {
            restrict: "AECM",
            template: "<h3>Hello, Directive, <span ng-transclude></span></h3>",
            replace: true,
            transclude: true
        };
        return option;
    })
<hello>12345678</hello>
//替换为了
<h3>Hello, Directive, <span ng-transclude=""><span class="ng-scope">12345678</span></span></h3>

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:'<div >{{title}}</div>'

    }
});
<div ng-controller="listCtrl">
    <input type="text"  ng-model="t" />
    <kid title="{{t}}" >  //这个必须指定的,这里的title是指令里scope的@对应的,t就是控制域scope下的
    <span>我的angularjs</span>
    </kid>
    </div> 

(2)=双向绑定

    <div ng-controller="listCtrl">
    <input type="text"  ng-model="t" />
    <kid title="t" > //和上面相比,这个直接赋值等于scope域下的t了
       <p>{{title}}</p>
       <span>我的angularjs</span>
       </kid>
    </div>
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            title:"="
        },
        template:'<div >{{title}}</div>'

    }
});

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

 <kid flavor="logchore(t)" ></kid>   
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            flavor:"&"
        },
        template:'<div >    <input type="text"  ng-model="v" /> <button ng-click="flavor({t:v})"></button></div>'
    }
});
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:
<span ng-controller="TimepickerDemoCtrl">
    <timepicker ng-model="mytime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></timepicker>
    </span>
//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作用域等

<body ng-app="components">
<h3>BootStrap Tab Component</h3>
<tabs>
    <pane title="First Tab">
        <div>This is the content of the first tab.</div>
    </pane>
    <pane title="Second Tab">
        <div>This is the content of the second tab.</div>
    </pane>
</tabs>
</body>
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:
            '<div class="tabbable">' +
            '<ul class="nav nav-tabs">' +
            '<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">'+
            '<a href="" ng-click="select(pane)">{{pane.title}}</a>' +
            '</li></ul>' +
            '<div class="tab-content" ng-transclude></div></div>',
            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:
            '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>',
            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...");
    });
}]);
//前端
<div ng-controller="LoadDataCtrl">
   <ul>
      <li ng-repeat="user in users">
         {{user.name}}
      </li>
   </ul>
</div>

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);
            }
        });
    }
]);
//前端
<div ng-controller="ServiceController">
  <label>用户名</label>
  <input type="text" ng-model="username" placeholder="请输入用户名" />
  <pre ng-show="username">{{users}}</pre>
</div>

四、页面跳转传参

$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是个共享的容器,比如购物车的使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,555评论 18 139
  • AngularJS是什么?AngularJs(后面就简称ng了)是一个用于设计动态web应用的结构框架。首先,它是...
    200813阅读 1,576评论 0 3
  • AngularJS AngularJS概述 介绍 简称:ng Angular是一个MVC框架 其他前端框架: Vu...
    我爱开发阅读 2,330评论 0 8
  • 指令定义 对于指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素的功能。  我们可以自己...
    oWSQo阅读 1,173评论 0 0
  • AngularJSAngularJS 是一个 MV* 框架, 最适于开发客户端的单页面应用。它不是个功能库,...
    一直以来都很好阅读 888评论 0 0