I15*_*159 7 javascript angularjs angularjs-directive
我在Angularjs上编写了一个非常复杂的应用程序.这已经足够让我迷惑了.我更深入地研究Angular,我发现我的代码很糟糕.我理解这个概念:
module.directive('createControl', function($compile, $timeout){
scope: {
// scope bindings with '=' & '@'
},
template: '<div>Template string with binded {{ variables }}</div>',
link: function(scope, element, attrs){
// Function with logic. Should watch scope.
}
Run Code Online (Sandbox Code Playgroud)
我有几个问题:
所以我的代码在简化视图中看起来像这样:
module.directive('createControl', function($compile, $timeout){
scope: {
var1: '@var1',
var2: '@var2',
var3: '@var3'
},
template: '<div>{{ var1 }} {{ var3 }}</div>',
link: function(scope, element, attrs){
$('.someelement').on('event', function(){
var2 = 'SNIPPET'; // Need to watch it
});
var3 = '<span>{{ var2 }}</span>';
}
})
Run Code Online (Sandbox Code Playgroud)
我的问题是:
如何使用范围变量编译我的模板?
如何观察范围变量?
我应该将我的指令拆分为两个吗?如果我应该,如何以正确的方式做到这一点?
过去几周发布的Angular 1.1.4增加template
了访问指令属性的能力:
例:
app.directive('mytest',function(){
return {
restrict:'E',
template:function( elem,attrs ){
return '<div>'+attrs.a+' '+attrs.b+'</div>';
}
}
});
Run Code Online (Sandbox Code Playgroud)
<mytest a="Hello" b="World"></mytest>
Run Code Online (Sandbox Code Playgroud)
请参阅1.1.4版的指令文档
我认为通过以下方式更改您的指令:
module.directive('createControl', function($compile, $timeout){
scope: {
var1: '=var1',
var2: '=var2',
var3: '=var3'
},
template: '<div>{{var1}} {{var3}}</div>',
link: function(scope, element, attrs){
$('.someelement').on('event', function(){
scope.var2 = 'SNIPPET'; // Need to watch it
});
/*I do not see what you want to do*/
scope.var3 = $compile('<span>{{var2}}</span>')(scope);
}
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20281 次 |
最近记录: |