Check if an object has a property
本问题已经有最佳答案,请猛点这里访问。
如何检查对象在AngularJS中是否具有特定属性?
You could use 'hasOwnProperty' to check if object have the specific
property.
1 2 3 4 5 | if($scope.test.hasOwnProperty('bye')){ // do this }else{ // do this then } |
这是jsFiddle中的一个演示。
希望这有帮助。
1 2 | if('bye' in $scope.test) {} else {} |
问题是,您可能不仅仅在链接您的指令时有值,例如$http可以加载它。
我的建议是:
1 2 3 4 5 6 7 | controller: function($scope) { $scope.$watch('test.hello', function(nv){ if (!nv) return; // nv has the value of test.hello. You can do whatever you want and this code // would be called each time value of 'hello' change }); } |
或者,如果您知道该值只分配了一个:
1 2 3 4 5 6 7 | controller: function($scope) { var removeWatcher = $scope.$watch('test.hello', function(nv){ if (!nv) return; // nv has the value of test.hello. You can do whatever you want removeWatcher(); }); } |
此代码将删除watcher分配的"test.hello"值(从任何控制器、Ajax等)