<repo_name>binwick/angularjs-learning<file_sep>/code/041-jquery/app/index.js
var app = angular.module('app', []);
app.controller('firstController', ['$scope', '$filter', '$location', '$anchorScroll', function ($scope, $filter, $location, $anchorScroll) {
    $('.multiple_upldprev:last').each(function () {
        // alert(1);
    });
    $scope.color = {};
    $scope.color.name = 'x';

    var data = [{id: '124', name: 'ttt', MeasureDate: "2015-04-05T18:46:38"},
        {id: '589', name: 'mmm', MeasureDate: "2015-05-05T18:46:38"},
        {id: '45', name: 'yyy', MeasureDate: "2016-01-05T18:46:38"},
        {id: '567', name: 'eee', MeasureDate: "2016-05-05T18:46:38"}];

    var sorted = data.sort(function (a, b) {
        return Date.parse(b.MeasureDate) - Date.parse(a.MeasureDate);
    });

    $('li').sort(function (a, b) {
        var aDate = $(a).find('.itemDate').text();
        var bDate = $(b).find('.itemDate').text();
        // return Date.parse(aDate) - Date.parse(bDate);
        return new Date(aDate).getTime() - new Date(bDate).getTime();
    }).appendTo('ul');

    console.log(sorted);

    $scope.items = {
        1: {
            "John": 123,
            "Doe": 234
        },
        2: {
            "John": 456,
            "Doe": 345
        }
    };
    // $("#btn_click").attr('disabled', true);

    $scope.test = function () {
        var tmp = JSON.jsonToString($scope.item);
        console.log(tmp);
        return tmp;
    }
    var jsonToString=typeof JSON !="undefined"? JSON.stringify :function(obj){
        var arr =[];
        $.each(obj,function(key, val){
            var next = key +": ";
            next += $.isPlainObject(val)? jsonToString(val): val;
            arr.push( next );
        });
        return"{ "+  arr.join(", ")+" }";
    };
}]);<file_sep>/code/035-Cookie/app/index.js
angular.module('myApp', ['ngCookies'])

    .filter('cityFilter', function () {
        return function (data, parent) {
            var filterData = [];
            angular.forEach(data, function (obj) {
                if (obj.parent === parent) {
                    filterData.push(obj);
                }
            })

            return filterData;
        }
    })

    .directive('even', function () {
        return {
            require: 'ngModel',
            link: function (scope, elm, attrs, ngModelController) {
                ngModelController.$parsers.push(function (viewValue) {
                    if (viewValue % 2 === 0) {
                        ngModelController.$setValidity('even', true);
                    } else {
                        ngModelController.$setValidity('even', false);
                    }
                    return viewValue;
                });

//                ngModelController.$formatters.push(function(modelValue){
//                    return modelValue + 'kittencup';
//                })
            }
        };
    })

    .directive('customTextArea', function () {
        return {
            restrict: 'E',
            template: '<div contenteditable="true"></div>',
            replace: true,
            require: 'ngModel',
            link: function (scope, elm, attrs, ngModelController) {


                // view->model
                elm.on('keyup', function () {
                    scope.$apply(function () {
                        ngModelController.$setViewValue(elm.html());
                    });
                })

                ngModelController.$render = function () {
                    elm.html(ngModelController.$viewValue);
                }

            }
        };
    })
    .controller('firstController', ['$scope', '$cookies', '$cookieStore', function ($scope, $cookies, $cookieStore) {
        // $cookieStore.put("name", "my name");
        // $cookieStore.get("name") == "my name";
        // $cookieStore.remove("name");

        // $cookieStore.put("person", {
        //     name: "my name",
        //     age: 18
        // });
        //
        // $cookieStore.put('person', {
        //     name: "<NAME>",
        //     age: 23
        // });

        // 设置带参数的cookie
        var now = new Date(),
            expireDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() + 1, now.getSeconds());
        // expireDate.setDate(expireDate.getDate() + 1);
        console.log(expireDate.toUTCString());
        $cookies.putObject('person', {
            name: "new new name",
            age: 24
        }, {
            'expires': expireDate
        });


        $scope.person = $cookieStore.get("person");
        console.log($scope.person);
    }]);
<file_sep>/code/029-自定义指令 controller && controllAs属性/app/index.js
angular.module('myApp', [])

    .directive('bookList', function () {
        return {
            restrict: 'ECAM',
            controller: ['$scope', function ($scope) {
                $scope.books = [
                    {
                        name: 'php'
                    }, {
                        name: 'javascript'
                    }, {
                        name: 'java'
                    }
                ];
                /**
                 * 如果这里写$scope.addBook
                 * 那么调用的时候用scope.addBook
                 */
                $scope.addBook = function () {
                    console.log('scope')
                };

                /**
                 * 如果用this.addBook
                 * 调用的时候使用bookListController.addBook
                 */
                this.addBook = function () {
                    // ...
                    console.log('this')
                };
            }],
            controllerAs: 'bookListController',
            template: '<ul><li ng-repeat="book in books">{{book.name}}</li></ul>',
            replace: true,
            link: function (scope, element, attrs, bookListController) {
                // 绑定事件
                element.on('click', bookListController.addBook)
            }
        }

    })

    .controller('firstController', ['$scope', function ($scope) {
        // console.log($scope);


    }]);<file_sep>/code/002/app/index.js
var app = angular.module('app', ['ng-sortable']);

app.controller('firstController', ['$scope', '$filter', function ($scope, $filter) {
    $scope.items = ['zhangSan', 'liSi', 'wangWu'];
    $scope.foo = ['foo 1', 'foo 2'];
    $scope.bar = ['bar 1', 'bar 2'];
    $scope.barConfig1 = {
        group: 'foobar',
        animation: 150,
        //onSort: function (evt) {
        //    console.log('onSort:', evt);
        //    console.log('items:', $scope.items);
        //    console.log('foo:', $scope.foo);
        //},
        //// Element is removed from the list into another list
        onRemove: function (evt) {
            // same properties as onUpdate
            console.log('onRemove:', evt);
        },
        onAdd: function (evt) {
            console.log('onAdd', evt);
        },
        //
        //// Attempt to drag a filtered element
        //onFilter: function (/**Event*/evt) {
        //    var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
        //    console.log('onFilter:', itemEl);
        //},

        // Event when you move an item in the list or between lists
        //onMove: function (/**Event*/evt) {
        //    // Example: http://jsbin.com/tuyafe/1/edit?js,output
        //    //console.log(evt.dragged); // dragged HTMLElement
        //    //console.log(evt.draggedRect); // TextRectangle {left, top, right и bottom}
        //    //console.log(evt.related); // HTMLElement on which have guided
        //    //console.log(evt.relatedRect); // TextRectangle
        //    // return false; — for cancel
        //    console.log('onMove:', evt)
        //}
    };
    $scope.barConfig2 = {
        group: 'foobar',
        animation: 150,
        onRemove: function (evt) {
            // same properties as onUpdate
            console.log('onRemove:', evt);
        },
        onAdd: function (evt) {
            console.log('onAdd', evt);
        },

    };
}]);<file_sep>/code/001/app/index.js
var app = angular.module('app', []);
//angular-directive
app // app 模块
    .directive('bsDatepicker', function ($filter) {
        return {
            restrict: 'A',
            scope: {
                date: "=ngModel"
            },
            link: function (scope, element, attrs) {
                element.parent().datetimepicker({
                    locale: 'zh-CN',
                    format: 'YYYY-MM-DD HH:mm:ss',
                    sideBySide: false,
                    showClear: false
                });
                console.log(scope.date);
                var format = attrs['dateFormat'];
                element.parent().on('dp.change', function (e) {
                    console.log(scope.date);
                    if (e.date) {
                        var newDate = new Date(e.date);
                        scope.$apply(function () {
                            scope.date = $filter('date')(newDate, format);
                        });
                    }
                });

            }
        }
    })
    .controller('firstController', ['$scope', '$filter', function ($scope, $filter) {
        $scope.date = 'zhangsan';


        //angular.element('#datetimepicker1').datetimepicker({
        //    format: 'YYYY-MM-DD HH:mm:ss',
        //    locale: 'zh-CN'
        //});
        //angular.element('#datetimepicker1').on('dp.change', function (e) {
        //    $scope.$apply(function () {
        //        $scope.date = $filter('date')(new Date(e.date), 'yyyy-MM-dd HH:mm:ss')
        //    })
        //});
    }]);<file_sep>/code/038-$anchorScroll tooltip/app/index.js
var app = angular.module('app', []);


app.run(['$anchorScroll', function ($anchorScroll) {

    $anchorScroll.yOffset = -50;   // 总是滚动额外的50像素

}]);
app.controller('firstController', ['$scope', '$filter', '$location', '$anchorScroll', function ($scope, $filter, $location, $anchorScroll) {

    $scope.gotoBottom = function () {

        // 将location.hash的值设置为
        // 你想要滚动到的元素的id
        $location.hash('bottom');

        // 调用 $anchorScroll()
        $anchorScroll();

    };
    $scope.amount = 123456;
    $scope.tooltipAmount = '';
    var termAmounts = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿'];

    var amount = $scope.amount.toString();
    if (amount.lastIndexOf('.') != -1) {
        $scope.tooltipAmount = termAmounts[amount.substr(0, amount.lastIndexOf('.')).length - 1];
    } else {
        $scope.tooltipAmount = termAmounts[amount.length - 1];
    }
}]);<file_sep>/code/037-$timeout/app/index.js
//为我们的demo创建一个应用模块
var app = angular.module("Demo", []);

// 定义控制器
app.controller("DemoController", ['$scope', function ($scope) {
    $scope.section = "happy";
    //在toggle函数中改变section的值，以此在标记中显示/隐藏不同的部分
    $scope.toggle = function () {

        if ($scope.section === "happy") {

            $scope.section = "sad";

        } else {

            $scope.section = "happy";

        }

    };

}
]);


//定义指令
app.directive("bnDirective", ['$timeout', function ($timeout) {
    //将用户界面的事件绑定到$scope上
    function link($scope, element, attributes) {
        //当timeout被定义时，它返回一个promise对象
        var timer = $timeout(function () {
            console.log("Timeout executed", Date.now());
        }, 2000);

        //将resolve/reject处理函数绑定到timer promise上以确保我们的cancel方法能正常运行
        timer.then(function () {
                console.log("Timer resolved!", Date.now());
            }, function () {
                console.log("Timer rejected!", Date.now());
            }
        );


        //当DOM元素从页面中被移除时，AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器
        $scope.$on("$destroy", function (event) {
                $timeout.cancel(timer);
            }
        );

    }

    //返回指令的配置
    return ({
        link: link,
        scope: false
    });

}]);

//定义指令
app.directive("bnDirectiveAlt", ['$interval', function ($interval) {
    //将用户界面的事件绑定到$scope上
    function link($scope, element, attributes) {
        //当timeout被定义时，它返回一个promise对象
        var timer = $interval(function () {
            console.log("Interval executed", Date.now());
        }, 10 * 1000);

        //将resolve/reject处理函数绑定到timer promise上以确保我们的cancel方法能正常运行
        timer.then(function () {
                console.log("Timer resolved!", Date.now());
            }, function () {
                console.log("Timer rejected!", Date.now());
            }
        );


        //当DOM元素从页面中被移除时，AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器
        $scope.$on("$destroy", function (event) {
                $interval.cancel(timer);
            }
        );

    }

    //返回指令的配置
    return ({
        link: link,
        scope: false
    });

}]);<file_sep>/code/028-自定义指令 compile && link属性/app/index.js
var i = 0;

var myApp = angular.module('myApp', [])

    .directive('customTags', function () {
        return {
            restrict: 'ECAM',
            template: '<div>{{user.name}}</div>',
            replace: true,
            compile: function (tElement, tAttrs, transclude) {

                tElement.append(angular.element('<div>{{user.name}}{{user.count}}</div>'));

                // 编译阶段...
                console.log('customTags compile 编译阶段...');

                return {
                    // 表示在编译阶段之后，指令连接到子元素之前运行
                    pre: function preLink(scope, iElement, iAttrs, controller) {
                        console.log('customTags preLink..')
                    },
                    // 表示在所有子元素指令都连接之后才运行
                    post: function postLink(scope, iElement, iAttrs, controller) {

                        iElement.on('click', function () {
                            scope.$apply(function () {
                                scope.user.name = 'click after';
                                scope.user.count = ++i;
                                // 进行一次 脏检查
                            });
                        })

                        console.log('customTags all child directive link..')
                    }
                }
                // 可以直接返回 postLink
                // return postLink function(){
                // console.log('compile return fun');
                //}
            },
            // 此link表示的就是 postLink
            link: function () {
//                iElement.on('click',function(){
//                    scope.$apply(function(){
//                        scope.user.name = 'click after';
//                        scope.user.count = ++i;
//                        // 进行一次 脏检查
//                    });
//                })
            }
        }
    })

    .directive('customTags2', function () {
        return {
            restrict: 'ECAM',
            replace: true,
            compile: function () {
                // 编译阶段...
                console.log('customTags2 compile 编译阶段...');

                return {
                    // 表示在编译阶段之后，指令连接到子元素之前运行
                    pre: function preLink() {
                        console.log('customTags2 preLink..')
                    },
                    // 表示在所有子元素指令都连接之后才运行
                    post: function postLink() {
                        console.log('customTags2 all child directive link..')
                    }
                }

            }
        }
    })


    .directive('customTags3', function () {

        // return postLink;
        return function () {

        }
    })

    .controller('firstController', ['$scope', function ($scope) {
        $scope.users = [
            {
                id: 10,
                name: '张三'
            },
            {
                id: 20,
                name: '李四'
            }
        ];
    }]);<file_sep>/code/032-练习 自定义accordion指令/app/index.js
angular.module('myApp', [])
    // 数据
    .factory('Data', function () {
        return [
            {
                title: 'no1',
                content: 'no1-content'
            },
            {
                title: 'no2',
                content: 'no2-content'
            },
            {
                title: 'no3',
                content: 'no3-content'
            }
        ];
    })
    // 控制器
    .controller('firstController', ['$scope', 'Data', function ($scope, Data) {
        $scope.data = Data;
    }])
    .directive('kittencupGroup', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="panel-group" ng-transclude></div>',
            transclude: true,
            controllerAs: 'kittencupGroupContrller',
            controller: function () {
                this.groups = [];

                this.closeOtherCollapse = function (nowScope) {
                    angular.forEach(this.groups, function (scope) {
                        if (scope !== nowScope) {
                            scope.isOpen = false;
                        }
                    })
                }
            }
        }
    })
    .directive('kittencupCollapse', function () {
        return {
            restrict: 'E',
            replace: true,
            require: '^kittencupGroup',
            templateUrl: 'app/tmp/kittencupCollapse.html',
            scope: {
                heading: '@'
            },
            transclude: true,
            link: function (scope, element, attrs, kittencupGroupContrller) {
                scope.isOpen = false;

                scope.changeOpen = function () {
                    scope.isOpen = !scope.isOpen;

                    kittencupGroupContrller.closeOtherCollapse(scope);
                };

                // group 放所有的 scope
                kittencupGroupContrller.groups.push(scope);
            }
        }
    });