指令 - 控制器中的数据绑定AngularJS [英] Directive - controller data binding in AngularJS

查看:83
本文介绍了指令 - 控制器中的数据绑定AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与现在这个挣扎小时。

I'm struggling with this for hours now.

var testApp = angular.module('testApp', []);

testApp.directive('test', function() {
    return {
        restrict: 'E',
        transclude: true,
        template: '<div ng-transclude>Hello World</div>',
        link: function(scope) {

        }
    }
});

testApp.controller('testCtrl', function ($scope) {
    $scope.user = "";
});

下面是的jsfiddle: http://jsfiddle.net/2bKPj/

Here's JSFiddle: http://jsfiddle.net/2bKPj/

现在,我需要的是嵌入在指令的输入,能够直接在testCtrl控制器反映用户模型。
我在此兽是如何工作的困惑,因为我教导说作用域在这种情况下共享的,不是吗?

Now, all I need is for an input embedded in directive to be able to reflect user model directly in testCtrl controller. I'm confused on how this beast works since I taught that scopes are shared in this case, no?

推荐答案

ngTransclude 创建一个新的子范围,其中protorypically继承它的父范围。

ngTransclude creates a new child scope which protorypically inherits from it's parent scope.

当您使用原始的子作用域它屏蔽了该父范围的变量。

When you use a primitive on the child scope it shadows the parent scope's variable.

它已经说过一千遍:使用点表示法

控制器:

testApp.controller('testCtrl', function ($scope) {
    $scope.data = { user : "Hello World" };
});

HTML:

<input type="text" ng-model="data.user"/><br />
Directive model:<span>{{ data.user }}</span>  

检查我的其他答案的说明:


  • bound里面ngIf元素不更新绑定

  • Directives里面NG-包括

  • Check my other answers for description:

    • bound element inside ngIf does not update binding
    • Directives inside ng-include
    • 这篇关于指令 - 控制器中的数据绑定AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆