2015-01-08 128 views
3

我想從指令的屬性中暴露多個值到$ scope。 的指令是動態生成的,看起來像這個例子:Angular指令:從指令到範圍的多個值

<my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive> 

我需要在$範圍值,他們給的模板,並與他們合作。

回答

4

容易... :-)

var app = angular.module('app', []); 
 
app.controller('myCtrl', function ($scope) {}); 
 
app.directive('myDirective', function() { 
 
    return { 
 
    restrict: 'E', 
 
    template: '<p>myDirective:</p>{{firstValue}}, {{secondValue}}, {{thirdValue}}', 
 
    scope: { 
 
     firstValue: '@', 
 
     secondValue: '@', 
 
     thirdValue: '@' 
 
    }, 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app"> 
 
    <div ng-controller="myCtrl"> 
 
    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive> 
 
    </div> 
 
</div>

但你真的應該嘗試寫這樣的代碼自己,下一次...... :-)

1

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

 
app.controller('homeCtrl', function ($scope) { 
 

 

 
    
 

 
}); 
 
app.directive('myDirective', function() { 
 

 
    return { 
 
    restrict: 'AE', 
 
    template: '<h3>My Directive</h3><p>{{firstValue}}|{{secondValue}}|{{thirdValue}}</p>', 
 
    scope: { 
 
     firstValue: '@', 
 
     secondValue: '@', 
 
     thirdValue: '@' 
 
    }, 
 

 
    link: function(scope, element, attr) { 
 

 
     console.log(scope.firstValue) 
 
     console.log(scope.secondValue) 
 
     console.log(scope.thirdValue) 
 

 
    } 
 

 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app"> 
 
    <div ng-controller="homeCtrl"> 
 

 
    <my-directive first-value="foo" second-value="bar" third-value="foobar"></my-directive> 
 
    </div> 
 
</div>