我创建了一个AngularJS指令,如下所示。
在关联的控制器中,我将变量text
的值计算为"SomeText"
。我希望此文本替换指令的Hello World!!
属性中的template
。我该怎么办?
我的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!!'
};
}
);
我的控制器:
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";
}
});
});
答案 0 :(得分:4)
由于您使用(function(){
angular.module('myapp',[])
//define controller and inject $http service as dependency.
.controller('ajax',['$http','$scope',function($http,$scope){
$http.get('0.0.0.0:8000/json/').success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
});
}])
})();
配置,因此您只需将controllerAs: 'directiveCtrl'
指定为控制器的变量(self),它就可以在模板中使用。
Pascal Precht撰写了相当广泛的explanation about controllerAs。
控制器
"SomeText"
指令
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";
}
});
});
答案 1 :(得分:3)
使用范围。绑定文本&#39; Hello World&#39;到范围变量( data )并将其作为{{data}}绑定到模板中。从控制器更改范围变量的值。
看看这个fiddle
<强>指令强>
myApp.directive('mypDirective', function() {
return {
restrict: 'E',
scope: {
myarg: '='
},
controller: 'DirectiveCtrl',
controllerAs: 'directiveCtrl',
bindToController: true,
template: '{{data}}',
link: function(scope, elem, attr, directiveCtrl) {
scope.data = "Hello World!!!"
}
};
});