angular1 學習

 

一、若是頁面上指明瞭應用和控制層(ng-app/ng-controller),主要是ng-app的值不爲空的時候,就須要用js去定義和控制應用,初始化數據javascript

<div ng-app="my-app" ng-controller="myCtro">
  <p>名字 : <input type="text" ng-model="name"></p>
  <h1>Hello {{name}}</h1>
</div>
<script>
    var app = angular.module("my-app",[]);
    app.controller("myCtro", function($scope) {
        $scope.name = "";
    })
</script>

二、循環(ng-repeat)php

三、自定義指令(directive)vue

要調用自定義指令,HTML 元素上須要添加自定義指令名。java

使用駝峯法來命名一個指令, runoobDirective, 但在使用它時須要以 - 分割, runoob-directive:angularjs

<runoob-directive></runoob-directive>

<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
    return {
        template : "<h1>自定義指令!</h1>"
    };
});
</script>

調用指令:chrome

  • 元素名(E)
    <runoob-directive></runoob-directive>
  • 屬性(A)
    <div runoob-directive></div>
  • 類名(C)
    <div class="runoob-directive"></div>
  • 註釋(M)
    <!-- directive: runoob-directive -->

    注意:能夠經過添加 restrict 屬性,並設置值,來設置指令只能經過屬性的方式來調用數組

    app.directive("runoobDirective", function() {
        return {
            restrict : "A",
            template : "<h1>自定義指令!</h1>"
        };
    });

  指令也能夠傳參數,放在scope裏面promise

phonecatApp.directive('isolateScope', function () {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      data: '@'
    },
    template: '<h3>{{data}}</h3>'
  }
})

<isolate-scope data="{{name}}"></isolate-scope>
 

四、模型(ng-model)app

五、做用域ide

  (1)$scope

  有一個reset() 時間,重置掉輸入的。

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>
 
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});

  (2)$rootScope(根做用域)

六、請求($http)

  在1.5之後$http 的 success 和 error 方法已廢棄。使用 then 方法替代。

var app = angular.module('myApp', []);
    
app.controller('siteCtrl', function($scope, $http) {
    $http({
        method: 'GET',
        url: 'https://www.runoob.com/try/angularjs/data/sites.php'
    }).then(function successCallback(response) {
            $scope.names = response.data.sites;
        }, function errorCallback(response) {
            // 請求失敗執行代碼
    });
  
});

  在$http({})中,使用post請求的時候,data若是是對象的話,須要加上transformRequest,目的在於把參數轉成序列化的格式,若是不用這個參數的話,能夠在使用的時候,事先將data轉成序列化的形式

$http({    
            method: "POST",    
            url: "",    
            data: id,    
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },    
            transformRequest: function(obj) {    
                var str = [];    
                for (var p in obj) {    
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    
                }    
                return str.join("&");    
            }  
})

 

七、選擇框

  使用如下形式更好,對選擇的值是對象的時候,應用更加靈活

<div ng-app="myApp" ng-controller="myCtrl">

<p>選擇網站:</p>

<select ng-model="selectedSite">
<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>
</select>

<h1>你選擇的是: {{selectedSite}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.sites = [
        {site : "Google", url : "http://www.google.com"},
        {site : "Runoob", url : "https://www.runoob.com"},
        {site : "Taobao", url : "http://www.taobao.com"}
    ];
});
</script>

  ng-options 使用對象有很大的不一樣,使用對象做爲數據源, x 爲鍵(key), y 爲值(value):ng-options="x for (x, y) in sites"

$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
};

八、表格

  表格的顯示序號能夠用$index表示

  區分奇偶的:$odd、$even

九、ng-disabled

  直接綁定應用程序數據到 HTML 的 disabled 屬性

  ng-show/ng-hide

  隱藏或顯示一個 HTML 元素

十、ng-click

  定義了 AngularJS 點擊事件

十一、ng-switch

<div ng-switch="myVar">
  <div ng-switch-when="dogs">
     <h1>Dogs</h1>
     <p>Welcome to a world of dogs.</p>
  </div>
  <div ng-switch-when="tuts">
     <h1>Tutorials</h1>
     <p>Learn from examples.</p>
  </div>
  <div ng-switch-when="cars">
     <h1>Cars</h1>
     <p>Read about cars.</p>
  </div>
</div>

十二、輸入驗證

  

1三、組件模板

默認狀況下,組件$ctrl用做控制器別名,但若是須要,咱們能夠覆蓋它。

phonecatApp.component("myTest", {
    template: `
        <p>1232 {{$ctrl.user}}</p>
        <span>23</span>
    `,
    controller: function() {
        var ctrl = this;
        ctrl.user = 'world';
    }
});

1四、過濾器

  

  自定義的話,使用filter:

<div ng-app="myApp" ng-controller="myCtrl">


姓名: {{ msg | reverse }}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.msg = "Runoob";
});
app.filter('reverse', function() { //能夠注入依賴
    return function(text) {
        return text.split("").reverse().join("");
    }
});
</script>

1五、服務

  (1)$location

    返回當前頁面的 URL 地址

  (2)$http

  (3)$timeout 

    對應了 JS window.setTimeout 函數

  (4)$interval

    對應了 JS window.setInterval 函數

  (5)自定義服務

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});

1六、子父組件之間的傳值

  (1)子組件向父組件傳值($emit:向上分發,子做用域向父做用域)

// 子組件
$scope.$emit('emit',"test");

// 父組件
$scope.$on ('emit', function(e, newName) {
      console.info(newName)
});

  (2)$broadcast:向下廣播,父做用域向子做用域

  (3)在子組件的bindings中定義一個方法,該方法傳給父組件的時候可傳參數

// 子組件
ctrl.onPostChildren({childrens:data.data})

// 父組件
元素上: on-post-children='showChildrens(childrens)
js上: $scope.showChildrens=function(childrens){
        $scope.children_list_ = childrens;
     }

1七、依賴注入

  依賴注入步驟:

  (1)value

    一個簡單的 javascript 對象,用於向控制器傳遞值(配置階段)

// 建立 value 對象 "defaultInput" 並傳遞數據
app.value("defaultInput", 5);


// 將 "defaultInput" 注入到控制器
app.controller('CalcController', function($scope, CalcService, defaultInput) {
});

  (2)factory

    是一個函數用於返回值。在 service 和 controller 須要時建立,一般咱們使用 factory 函數來計算或返回值。

// 建立 factory "MathService" 用於兩數的乘積 provides a method multiply to return multiplication of two numbers
app.factory('MathService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   return factory;
}); 

  (3)service

// 在 service 中注入 factory "MathService"
app.service('CalcService', function(MathService){
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

  (4)provider 

    經過 provider 建立一個 service、factory等(配置階段)。

    Provider 中提供了一個 factory 方法 get(),它用於返回 value/service/factory

// 使用 provider 建立 service 定義一個方法用於計算兩數乘積
app.config(function($provide) {
   $provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {};  
         
         factory.multiply = function(a, b) {
            return a * b; 
         }
         return factory;
      };
   });
});

  (5)constant(常量)用來在配置階段傳遞數值,注意這個常量在配置階段是不可用的

app.constant("configParam", "constant value");

 1八、監聽參數的變化($watch)

$scope.$watch('name', function(newValue, oldValue) {  
    console.info(newValue, oldValue)
  }); 

 1九、transclude/ng-transclude 至關於vue中的solt

好比:在buttonBar指令中,它提供了一個transclude:true屬性,同時在它的模板裏面使用ng-transclude指令。執行以後,在運行的過程當中,Angular獲取到自定義指令的內容,處理完了以後把結果放到了模板中連接上ng-transclude的div。

transclude單個位置:

phonecatApp.directive('primary', function() {
  return {
      restrict: 'AC',
      link: function(scope, element, attrs) {
          element.addClass('btn btn-primary');
      }
  }
});

phonecatApp.directive('buttonBar', function() {
  return {
      restrict: 'EA',
      template: `<div class="span4 well clearfix">
      <div class="pull-left" ng-transclude></div>
      </div>`,
      replace: true,
      transclude: true
  };
});
<button-bar>
        <button class="primary">Primary1</button>
     <button primary>Primary2</button>
</button-bar>

 transclude到多個位置:

phonecatApp.directive('btnPrimary', function() {
  return {
      restrict: 'AC',
      link: function(scope, element, attrs) {
          element.addClass('btn btn-primary');
      }
  }
});

phonecatApp.directive('btnInfo', function() {
  return {
      restrict: 'AC',
      link: function(scope, element, attrs) {
          element.addClass('btn btn-info');
      }
  }
});

phonecatApp.directive('buttonBar', function() {
  return {
      restrict: 'EA',
      template: `<div class="span4 well clearfix">
      <div class="pull-left" ng-transclude="left"></div>
      <div class="pull-right" ng-transclude="right"></div>
      <div ng-transclude>我是模版中的默認插入點的內容</div>
      </div>`,
      replace: true,
      transclude: {
          left: "?buttonsLeft", // 這裏若是不加?的話,在使用該指令的時候必定要有這個
          right: "?buttonsRight",
      }
  };
});
<button-bar>
      <buttons-left>
        <button class="btn-primary" ng-click="onPrimary1Click()">{{primary1Label}}</button>
        <button btn-primary>Primary2</button>
      </buttons-left>
      <buttons-right>
          <button btn-info>Primary3</button>
      </buttons-right>
      <button class="btn btn-danger">默認</button>
</button-bar>

20、$q

  是angular本身封裝實現的一種promise的實現。

  (1)$q.defer(); 建立一個deferred對象,這個對象能夠執行幾個經常使用的方法,好比:resolve、reject、notify等

  (2)$q.all()傳入Promise的數組,批量執行,返回一個Promise對象

  (3)$q.when();傳入一個不肯定的參數,若是符合Promise標準,就返回一個promise對象

phonecatApp.service('taskList', function ($http, $q) {
  var deferred = $q.defer();

  $http.post(RD.kpUrl + "do")
    .then(function (data) {
      deferred.resolve(data);
    })
  return deferred.promise;
})

調用:
phonecatApp
.controller('evaluateCtrl', function (taskList) {
taskList.then(function (data) {})
});

 2一、$eval

$eval是scope對象上的一個方法,用來解析表達式的。

好比在$scope中定義了一個變量,其中變量名有的是動態的話,在頁面渲染的時候,須要作下面的轉義

$scope.name1 = "$eval111";
$scope.name2 = "$eval222";

<ul>
      <li ng-repeat="arr in [1,2]">{{$eval('name'+($index+1))}}</li>
</ul>

 2二、unsafe

好比給a標籤的href用變量,會生成一個unsafe:javascript:void(0)

$scope.nhref="javascript:void(0)";

<a ng-href="{{nhref}}">測試</a>

這樣對於chrome是無所謂的, 可是firefox就把它當成一個新的地址跳轉了, 這不是咱們預期的, 因此必須去掉unsafe:這個前綴.

phonecatApp.config([
  '$compileProvider',
  function ($compileProvider) {
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|javascript|mailto|tel|file|sms):/);
  }
])

 

 

查看angular的版本,在項目裏面運行命令行:ng -v angularjs

相關文章
相關標籤/搜索