我想去树模型对象。
但是每个子树都有不同的结构,并且每隔1秒附加一个孩子。
我写信给:
HTML ::
<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();
});
问题:
答案 0 :(得分:0)
您应该在链接功能中添加一个观察者而不是控制器功能,并用简单的手表替换$ attrs.watch
替换
controller:function($scope, $element, $attrs){
$scope.$watch($attrs.obj, function(value) {
with -
link:function($scope, $element, $attrs){
$scope.$watch('obj', function(value) {