【问题标题】:Directive - controller data binding in AngularJS指令 - AngularJS 中的控制器数据绑定
【发布时间】:2014-02-02 23:29:35
【问题描述】:

我已经为此苦苦挣扎了好几个小时。

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/

现在,我所需要的只是嵌入指令中的输入,以便能够直接在 testCtrl 控制器中反映用户模型。 我对这个野兽的工作原理感到困惑,因为我教过在这种情况下范围是共享的,不是吗?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    ngTransclude 创建一个新的子作用域,它以原型方式继承自它的父作用域。

    当您在子作用域上使用原语时,它会隐藏父作用域的变量。

    已经说过千百遍了:使用点符号!

    控制者:

    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>  
    

    查看我的其他答案以了解说明:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      相关资源
      最近更新 更多