我创建了一个 AngularJS 指令,如下所示。
在关联的 Controller 中,我将变量 text
的值计算为 "SomeText"
。我希望此文本替换指令的 template
属性中的 Hello World!!
。我该怎么做?
我的 HTML:
<myp-directive myarg="myObject"></myp-directive>
我的指令:
myApp.directive('mypDirective',function(){
return {
restrict:'E',
scope: {
myarg: '='
},
controller: 'DirectiveCtrl',
controllerAs: 'directiveCtrl',
bindToController: true,
template: 'Hello World!!'
};
}
);
我的 Controller :
myApp.controller('DirectiveCtrl', function($scope){
var self = this;
$scope.$watch(function() {return self.prediction;}, function (newVal, oldVal)
{
if (newVal !== oldVal && newVal !== null){
var text = "SomeText";
}
});
});
最佳答案
由于您使用了 controllerAs: 'directiveCtrl'
配置,您可以简单地将 "SomeText"
指定为 Controller (self)的变量,它将在模板。
Pascal Precht 写了相当广泛的 explanation about controllerAs .
Controller
myApp.controller('DirectiveCtrl', function($scope){
var self = this;
self.text = "Hello World!!";
$scope.$watch(function() {return self.prediction;}, function (newVal, oldVal)
{
if (newVal !== oldVal && newVal !== null){
self.text = "SomeText";
}
});
});
指令
myApp.directive('mypDirective',function(){
return {
restrict:'E',
scope: {
myarg: '='
},
controller: 'DirectiveCtrl',
controllerAs: 'directiveCtrl',
bindToController: true,
template: '{{directiveCtrl.text}}'
};
}
);
关于javascript - 在 AngularJS 中,如何将 Controller 的传递值返回到指令的模板属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067401/