AngularJS学习笔记

2017-08-14  本文已影响0人  段誉九段

引入angular.js

若在页面中引入了angular.js并添加了ng-app="app" ng-controller="ctrl",而没有实现模型,会报错:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

初始化变量

<div ng-app="" ng-init="firstName='John'">   
    <p>姓名为 <span ng-bind="firstName"></span></p>     
</div>
var app = angular.module('app', ['ngAnimate']);
app.controller('ctrl', function ($scope, $http) {
    $scope.step = 1;
    ...
});

防止载入过程中界面闪烁

添加属性:ng-cloak

<div class="mask" ng-show="show" ng-cloak>

IntelliJ不识别AngularJS、无自动提示的问题

使用http请求时,需声明使用http模块,否则会提示$http is not defined,其他模块类似

app.controller('ctrl', function ($scope, $http) {
    $scope.getX = function () {
        $http({
            method: 'GET',
            url: 'json/x.json'
        }).then(function success(response) {
            var status = response.data.status;
            ...
        }, function error(e) {
            console.log(e);
        });
    };
});

一个html页面只能加载一个ng-app的问题

  1. 可以简单的将多个 ng-app 合并成为一个根模块。
  2. 可以手动装载除了第一个以外的多个 ng-app。
    angular.bootstrap(document.getElementById("app2div"), ['myApp2']);

AngularJS操作cookie

    var app = angular.module('myApp', ['ngCookies']);
    app.controller('myCtrl', function ($scope, $http, $cookies) {
        $scope.foo = function () {
            $cookies.put('user', 'eric', {path: '/'});
        };
    });

注意:
一、默认情况下子目录下设置的cookie父目录页面读不到,需明确设置path
二、不要将$cookies写成$cookieStore

文档加载完成时执行

    $scope.$watch('$viewContentLoaded', function () {
        $scope.init();
    });
上一篇下一篇

猜你喜欢

热点阅读