angular使用经验

JSONP使用方法

$http.jsonp("http://wthrcdn.etouch.cn/weather_mini?callback=JSON_CALLBACK&city=北京")
        .then(function successCallback(response) {
                console.log(JSON.stringify(response));
            }, function errorCallback(response) {
                console.log(JSON.stringify(response));
        });

自建服务

有的时候我们需要建立自己的服务,而不是每次都在controller里面进行$http请求
自己的service不能以$开头,并且也可以注入controller,但是要放在最后一个
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');
            }
        };
    }
]);
$scope上面有一个$watch的方法 它可以监控数据模型的变化
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;
                            console.log(JSON.stringify(data))
                        });
                }, 350);
            }
        });
    }
]);

Ajax请求本地文件也需要跨域

本地跨域设置
但是从webstorm直接打开网页进行请求不存在这个问题 这个IDE内置服务器 详解

Paste_Image.png
Paste_Image.png
Paste_Image.png

搭建项目

步骤

UI-router

angular原生没法实现嵌套路由

run()

初始化全局的数据 , 只对全局作用域起作用 如 $rootScope,局部的$scope不管用,run方法类似于回调方法,在angular启动之后执行一些动作。

angular run()运行块
AngularJS中run方法的巧妙运用

一个APP可以写几个模块

你可能感兴趣的:(angular使用经验)