AngularJS:使用指令动态模板的树模型对象
我要遍历树模型对象 但每个子树都有不同的结构,每1秒都会追加一个子树 我写信给: HTML::AngularJS:使用指令动态模板的树模型对象,angularjs,dynamic,recursion,tree,directive,Angularjs,Dynamic,Recursion,Tree,Directive,我要遍历树模型对象 但每个子树都有不同的结构,每1秒都会追加一个子树 我写信给: HTML:: <div ng-app="myApp"> <div ng-controller="MainCtrl"> <input type="button" ng-click="init()" value="init"/> {{obj}} <hr /> obj:: <exa
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<input type="button" ng-click="init()" value="init"/>
{{obj}}
<hr />
obj::
<example obj="obj"></example>
<hr />
obj1::
<example obj="obj1"></example>
<hr />
obj1.id::
{{obj1.id|json}}
</div>
</div>
Javascript::
var app = angular.module('myApp', []);
app.directive('example', function () {
return {
restrict:"E",
trunslate: true,
scope:{
obj:'='
},
controller:function($scope, $element, $attrs){
$scope.$watch($attrs.obj, function(value) {
var template = "<ol>"; // dynamic template
console.log("OBJ :: ");
f = value;
console.log($scope.obj);
angular.forEach($scope.obj, function(value,field){
if(angular.isArray(value)){
template += '<li>'+field;
template += ' <div ng-repeat="sobj in obj.' + field + '">';
template += ' <example obj="sobj"></example>';
template += ' </div>';
template += '</li>';
}else{
template += '<li>' + field + "::" + value + "</li>";
}
});
template += "</ol>";
$element.replaceWith($element.html(template));
});
}
};
})
app.controller('MainCtrl', function ($scope) {
$scope.obj = {
ifdsfds:5,
fdsafds:'Nfdsafdase 1',
subobj:[{
id: 1,
val: 'hi'
}]
};
$scope.obj1 = {
id:5,
fdsafds:'Nfdsafdase 1'
};
$scope.init = function(){
$scope.obj = {
id: 1,
title: 'Nofdsafdste 61'
}
};
$scope.counter = 0;
$scope.ajax = function(){
var number = Math.round(Math.random()*100);
$scope.obj1.id = number;
//if($scope.counter++ < 10){
setTimeout(function(){
$scope.ajax();
$scope.$apply();
}, 3000);
//}
console.log($scope.counter + " = " + number);
};
$scope.ajax();
});
问题:
使用setTimeout每秒更改obj.id的模型。工作{{obj.id}}已更改。但不改变传递给指令的obj模型。
不工作的递归指令。
我不想使用模板字段
您应该在link函数而不是controller函数中添加一个watcher,并用simple watch替换$attrs.watch 替换
controller:function($scope, $element, $attrs){
$scope.$watch($attrs.obj, function(value) {
与-
link:function($scope, $element, $attrs){
$scope.$watch('obj', function(value) {
为什么你要在控制器中添加手表而不是链接功能??