Ron*_*nIL 3 angularjs angularjs-directive angularjs-service angularjs-scope
我正在AngularJS中盯着我.
我创建了一个自定义指令:
app.directive('myScroll',function(){
return {
restrict: 'A',
transclude: true,
template: '<div ng-transclude></div>',
link: function(scope , element , attrs) {
element.addClass('scroll-pane');
scope.$watch('tasks', function(newval, oldval){
if ( newval )
{
console.log(newval);
console.log(newval.length);
}
});
console.log("afer watch exper");
console.log (tasks);
}
};
Run Code Online (Sandbox Code Playgroud)
});
使用以下HTML:
<div my-scroll>
<ul>
<li data-ng-repeat="task in tasks" class="task-wrapper">
<div class="task-element">
<div class="name">{{task.name}}</div>
<div class="text">{{task.action}}</div>
</div>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
任务对象通过控制器调用的服务进行评估(如果需要,我将发布其代码).
在指令代码中,任务对象是未定义的,因为我必须得到任务长度来执行更多的css命令我必须等待ng-repeat完成或者只是等待任务变量将被评估.
由于某种原因,$ watch语句的外部和内部始终未定义任务.我可以在控制台中看到首先打印"看完经验后",然后是"在手表中",但仍然没有值.newval对象有[move2:function]但它的length属性保持返回0,但它保留了一系列资源和我的任务.
我在这里缺少什么以及如何在评估任务变量时执行命令?
谢谢你的帮助.
zs2*_*020 11
您应该scope.tasks用来引用数据.
app = angular.module('myApp', []);
app.directive('myScroll', function () {
return {
restrict: 'A',
transclude: true,
template: '<div ng-transclude></div>',
link: function (scope, element, attrs) {
element.addClass('scroll-pane');
scope.$watch('tasks', function (newval, oldval) {
if (newval) {
console.log(newval);
console.log(newval.length);
}
});
console.log("afer watch exper");
console.log(scope.tasks); //this will log the actual data.
}
};
});
function Ctrl($scope) {
$scope.tasks = [{
name: "task1",
action: "action1"
}]
}
Run Code Online (Sandbox Code Playgroud)
尝试传递第3个参数 - true到$ watch:
scope.$watch('tasks', function(newval, oldval){
if(newval){
console.log(newval);
console.log(newval.length);
}
},true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13365 次 |
| 最近记录: |