AngularJs directive-scope

来源:互联网 发布:sunny crown 人工智能 编辑:程序博客网 时间:2024/06/13 05:22

1.scope:bool 或者 object代码: 

<body ng-app="myApp">    <div ng-controller="myCtrl">        外部:{{myProperty}}        <input  ng-model="myProperty"/>        <br />        <div my-directive></div>    </div></body>
var app = angular.module('myApp', []);app.controller('myCtrl', function ($scope) {    $scope.myProperty = '张三';});app.directive('myDirective', function () {    return {        restrict: 'A',        scope: false, //继承但不隔离,控件内部,外部数据同步        //scope:true, //继承并隔离,即template内部变量修改,不影响外部        // scope:{}, //隔离且不继承        template: '<div class="bg-primary">内部:{{myProperty}} <input  class="text-primary" ng-model="myProperty"/> </div>'    }});


2.scope制定object绑定

<body ng-app="myApp">    <div class="container-fluid">        <div ng-controller="myCtrl">            外部:{{myProperty}}            <br />            <my-directive title="myProperty"></my-directive>        </div>    </div></body>
//定义模块,封装指令angular.module('common', []).directive('myDirective', function () {    return {        restrict: 'E',        //内部重新定义绑定字段名称        scope: {            //title: '@' //将标签定义的字符串,绑定显示            title:'=' //将指令内部scope字段和指令外部模块scope字段双向绑定        },        template: '<div class="bg-primary">内部:{{title}} <input  class="text-primary" ng-model="title"/> </div>'    }});//使用指令 myProperty对应外部绑定字段名称,title对应指令内部绑定名称var app = angular.module('myApp', ['common']);app.controller('myCtrl', function ($scope) {    $scope.myProperty = '张三';});

3.绑定页面,指定的字符串内容,代码:

<body ng-app="myApp">    <div side-box title="TagCloud">        <div class="tagcloud">            <a href="">Graphics</a>            <a href="">ng</a>            <a href="">D3</a>            <a href="">Front-end</a>            <a href="">Startup</a>        </div>    </div></body>

angular.module('myApp', [])    .directive('sideBox', function () {        return {            restrict: 'EA',            scope: {                title: '@'            },            transclude: true,            template: '<div class="sidebox"><div class="content"><h2 class="header">' +                '{{ title }}</h2><span class="content" ng-transclude></span></div></div>'        };    });


0 0