2014-12-30 116 views
0

要开始,我成立了一个的jsfiddle这里:http://jsfiddle.net/qLagkgt5/3/

我希望标题是明确的,但基本上,我试图使用指令来帮助重复的HTML。在JSFiddle的例子中,我使用了一个带有间距和框型选项的box指令。

,我变成重复的代码生成的HTML:

<div class="box"> 
    <div class="box-inner"> 
     {{CONTENT GOES HERE}} 
    </div> 
</div> 

随着选修课程:

<div class="box spacing-small box-rounded"> 
    <div class="box-inner"> 
     {{CONTENT GOES HERE}} 
    </div> 
</div> 

我想什么,能够做的是:

<box spacing="small" box-type="rounded"> 
    {{CONTENT GOES HERE}} 
</box> 

这是显然是一组非常简化的html,不一定需要指令,但它只是一个例子来说明我正在运行什么。

我们对事物的角度侧...

这里是我的控制器:

app.controller("Ctrl", ["$scope", function($scope) { 

    $scope.text = "Starting Text... FOOBAR!"; 

}]); 

这里是我的指令:

app.directive("box", function() { 
    return { 
     restrict: "E", 
     transclude: true, 
     replace: true, 
     scope: { 
      spacing: "@", 
      boxType: "@" 
     }, 
     template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>' 
    } 
}); 

如果我现在把我的指令放在html里面,像这样的控制器:

<div class="wrap" ng-controller="controller"> 
    {{text}} 
    <box spacing="small"> 
     <input ng-model="text"/> 
    </box> 
</div> 

的$ scope.text那就是<box>外面当我改变箱内输入永远不会更新。

  1. 如何使它在使用此指令时,框内的内容上升到父范围而不是隔离范围?
  2. 如果我在另一个框中嵌套一个框,我是否也可以将它放到同一个父范围内?

谢谢!

回答

0

我在阅读您的文章时立即在我的脑海中跳起来看到了一些关于stackoverflow的信息。它说“如果你做得没有点,你做错了......”我会搜索文章,并在发现它后立即发布它,但现在我想我“修复”你的代码:

<div ng-app="app" ng-controller="Ctrl"> 
    <h1><span class="grey">$scope.data.text:</span> {{data.text}}</h1> 
    <box spacing="large" box-type="rounded"> 
     <h2><span class="grey">$scope.text in box directive:</span> {{data.text}}</h2> 
     <input ng-model="data.text" /> 
    </box> 
    <box spacing="small" box-type="rounded-shadow"> 
     <h2><span class="grey">$scope.text in different box directive:</span> {{data.text}}</h2> 
     <input ng-model="data.text" /> 
    </box> 
</div> 

var app = angular.module("app", []); 

app.controller("Ctrl", ["$scope", function($scope) { 

    $scope.data = {}; 
    $scope.data.text = "Starting Text... FOOBAR!"; 

}]); 

app.directive("box", function() { 
    return { 
     restrict: "E", 
     transclude: true, 
     replace: true, 
     scope: { 
      spacing: "@", 
      boxType: "@" 
     }, 
     template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>' 
    } 
}); 

您必须创建一个对象并将其用于数据绑定。我现在使用“data.text”并用这个表达式进行绑定。

干杯, Tim。

P.S .:有很多链接。

要提只有两种:

AngularJS: If you are not using a .(dot) in your models you are doing it wrong?

AngularJS: dot in ng-model