AngularJs 的ng-include指令的使用

AngularJs經過指令ng-include來將頁面中共用的模塊分離出來,這個功能和mvc裏面的分部頁的做用同樣的。javascript

先看文件的結構:html

父頁面:java

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdn.staticfile.org/angular.js/1.7.5/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="ParentCtr">
    <div ng-include="'Childrens/Header.html'"></div>
    <input type="text" ng-model="test" />
    <p style="background-color:darkgoldenrod">這裏演示在一個HTML頁面中,經過引用子頁面來完成整個頁面功能</p>

    <div ng-include="'Childrens/Footer.html'"></div>
        <script type="text/javascript">
            var formapp = angular.module('myApp', []);
            formapp.controller('ParentCtr', function ($scope) {
                $scope.test = "hello";
                $scope.$on('to-parent', function (d, data) {
                    $scope.$broadcast('to-child', data);  
                });  
            })
                .controller("headerCtr", function ($scope) {
                    $scope.headerTitle = "頭部";
                    $scope.btnheader = function () {
                        $scope.headerTitle = "點擊了按鈕";
                    }
                    $scope.btnheader1 = function () {   
                        $scope.$emit('to-parent', $scope.headerTitle);                                             
                    }
                })
                .controller("footerCtr", function ($scope) {
                    $scope.ft = "尾部";
                    $scope.list = ["abc", "efg", "xyz"];
                    $scope.$on('to-child', function (d, data) {
                        $scope.fromHeader= data;
                    });  
                });
        </script>
</body>

</html>

子頁面Header.html: mvc

<div ng-controller="headerCtr">
    <h2>這是頭部</h2>
    <input ng-model="headerTitle" />
    <input type="button" ng-click="btnheader()" value="點擊我" />
    <input type="button" ng-click="btnheader1()" value="點擊我,將文本框的內容顯示到尾部" />
</div>

子頁面Footer.html:app

<div ng-controller="footerCtr">
    <h2>這是尾部</h2>
    <p>{{ft}}</p>
    <p>{{fromHeader}}</p>
    <ul>
        <li ng-repeat="t in list">{{t}}</li>
    </ul>
</div>

運行效果:函數

 在不一樣的控制器之間傳值比較麻煩,同級的控制器之間不能相互傳值,而是經過父級控制器來傳值。具體步驟:spa

當點擊頭部的按鈕的時候,經過 $scope.$emit('to-parent', $scope.headerTitle); 將要傳遞的數據傳遞到父級控制器,而後在父級控制器中,經過 $scope.$on('to-parent', function (d, data)來獲取數據,而後在函數中調用  $scope.$broadcast('to-child', data);code

將數據傳遞到子控制器,最後在子控制器中用$scope.$on('to-child', function (d, data) 來接收傳來的數據。orm

 若是想把js腳本單獨放到js文件中,能夠這樣:但要注意的是,全部的js文件的引用都是在父級頁面cdn

相關文章
相關標籤/搜索