加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJs directive-scope双向绑定方法处理-实例2

发布时间:2020-12-17 10:06:45 所属栏目:安全 来源:网络整理
导读:1.Html代码: div class="container-fluid" ng-app="myApp" div ng-controller="myCtrl" br /br / 外部:input ng-model="user.name" / br /br / my-directive my-user-data="user"/my-directive /div /div 2.Js代码: //定义模块,封装指令angular.module('c

1.Html代码:

    <div class="container-fluid" ng-app="myApp">
        <div ng-controller="myCtrl">
            <br /><br />
            外部:<input ng-model="user.name" />
            <br /><br />
            <my-directive my-user-data="user"></my-directive>
        </div>
    </div>

2.Js代码:
//定义模块,封装指令
angular.module('common',[])
.directive('myDirective',function () {
    return {
        restrict: 'E',//内部重新定义绑定字段名称
        scope: {
            myUserData: '=' //将指令内部scope字段和指令外部模块scope字段双向绑定
        },template: '<div class="bg-primary">内部:{{myUserData.name}} <input  class="text-primary" ng-model="myUserData.name"/> </div>',link: function (scope,elem,attr) {
            //定义双向绑定处理的字段和方法
            scope.myUserData = {
                name:'李四'
            };
            scope.myUserData.say = function () {
                console.info('hello');
            }
        }
    }
});
//使用指令 myUserData对应外部绑定字段名称,user对应指令内部绑定名称
var app = angular.module('myApp',['common']);
app.controller('myCtrl',function ($scope) {
    //在此处,执行方法,抛出异常 say还没有定义
    //$scope.user.say();
    setTimeout(function () {
        //在此处,指定方法,没有抛出异常 say已经定义
        $scope.user.say();
    },100);
});

结果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读