我通过指令将属性ng-bind='data'添加到元素中
myApp.directive('myDiv', function() {
return {
restrict: 'E',
link: function($scope, element, attrs) {
element.html('<div ng-bind="data">me</div>');
} }; });
function MyCtrl($scope) {
$('#click').click(function() {
$scope.data = 'change';
}); }但ng绑定并不像预期的那样有效。
http://jsfiddle.net/HB7LU/3427/
发布于 2014-05-02 14:27:37
要回答主要问题,这里的问题是,如果希望在模板中包含绑定,则需要编译元素。这方面的语法如下:
$compile(angular.element("my html"))(scope)在您的情况下,最终的结果是:
myApp.directive('myDiv', function($compile) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// here adding the ng-bind dynamically
element.html($compile(angular.element('<div ng-bind="data">me</div>'))(scope));
}
};
});要查看它的工作情况,请在这里查看更新的小提琴:http://jsfiddle.net/CC8BK/。
另一个注意事项是,您正在使用jQuery的"click“事件来更改范围值。在使用角时,您需要首先尝试不使用jQuery,而是使用任何您可以使用的角指令。在您的例子中,ng-click是您应该使用的指令。我把这个插入到html中,这样您就可以看到它的样子了。
希望这能让你走上正轨。祝你好运!
发布于 2014-05-02 14:39:52
正如@drew_w所说,如果需要从链接中应用,则必须使用$compile编译元素,
否则,您可以在方向中使用template,如
template: '<div ng-bind="data"></div>'我更喜欢模板
也不要像这样使用jquery函数
$('#click').click(function() {
$scope.data = 'change';
});相反,您可以使用
$scope.change = function()
{
$scope.data = 'change';
}或
ng-click="data = 'change'" 正如@drew_w所说
看一下完整的代码
工作演示
html
<div ng-controller="MyCtrl">Hello, {{name}}!
<button id='click' ng-click="change()">click to 'change'</button>
<my-div>watch, this doesn't change!!!???</my-div>
</div>脚本
var myApp = angular.module('myApp', []);
myApp.directive('myDiv', function ($compile) {
return {
restrict: 'E',
template:'<div ng-bind="data"></div>'
};
});
myApp.controller('MyCtrl', function ($scope) {
$scope.data = "me";
$scope.name = 'Superhero';
$scope.change = function () {
$scope.data = 'change';
}
});发布于 2014-05-02 14:33:51
下面是使用Template属性和使用click函数的上述答案的一个变体:
myApp.directive('myDiv', function() {
return {
restrict: 'E',
template:'<div ng-bind="data"></div> me'
};
});在控制器上:
$scope.click = function() {
$scope.data = 'change';
};论观点
<button ng-click="click()">click to 'change'</button>http://jsfiddle.net/HB7LU/3446/
https://stackoverflow.com/questions/23430333
复制相似问题