我想用angularjs和my97datepicker做一个东西,写了一个direcitve,在点击选择完时间之后,把值同步到scope上面。描述的有点乱,看下主要代码:
javascriptvar datepicker=angular.module("datepicker",[]); datepicker.controller("datepickerCtrl",function($scope){ $scope.date="2014-10-14"; }); datepicker.directive("datePicker",function(){ return { restrict:"A", link:function(scope,element,attr){ element.bind("click",function(){ window.WdatePicker(); }); //问题在这里,无法取到变化的值,而且加上这个,连初始的值都无法显示出来。 scope.$watch(attr.value,function(newVal){ scope.date=newVal; }); } }; });
在线地址:http://jsfiddle.sinaapp.com/4zz6nvadg/embedded。初学angularjs,每次写directive都是卡在$watch这里。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
不知道为何要这么用,这里你需要明确一个概念,属性和 scope 是不同的,如果要绑定属性值到 scope 中,需要在 directive 中去做 scope 的声明,有以下三种方式:
按照你的思路,可能是下面的方式:
但即使是做了绑定,还要明白这个元素的 value 的值变更并不是 Angular 默认会做监控的,
这个绑定只是说要去绑定这个属性值对应的变量,当然无法 watch 到 value 的变更。其实用 ng-model 和 ng-change 足够了。
最终可能是这样:
试试把$scope传进来!$watch是在$scope基础上的
没找到link的详细文档,不能确定attr的具体使用方法,不过觉得你可以试试$watch一下element的value。
至于楼上2位,在directive里scope就是它的$scope,attr是link里的一个参数,不需要另外定义。
楼主你好,请问这个问题最后如何解决,我现在是ng-model取到的值还是undefined