angularjs 指令未随范围更新。$watch
angularjs directive not upating with scope.$watch
我正在尝试根据控制器变量聚焦输入。它在控制台中正确初始化打印 value= false 并且控制器在视图中而不是在指令中更新变量。我正在使用 jade/coffeescript 或我创建了一个示例,但仅此而已:
控制器
$scope.autofocus = false
$scope.somefunction = ->
$scope.autofocus = true
指令。
'use strict'
angular.module('myapp')
.directive 'gsautofocus', ($timeout, $parse) ->
{
link: (scope, element, attrs) ->
model = $parse(attrs.gsautofocus)
scope.$watch model, (value) ->
console.log 'value=', value
if value == true
$timeout ->
element[0].focus()
return
return
}
查看
input(type="text", gsautofocus="{{autofocus}}")
您应该在属性上使用 $observe
,就像您想要评估每个摘要中的插值包含一样,$watch
不适用于插值。
$观察
$observe(key, fn);
Observes an interpolated attribute.
The observer function will be invoked once during the next $digest
following compilation. The observer is then invoked whenever the
interpolated value changes.
代码
'use strict'
angular.module('myapp')
.directive 'gsautofocus', ($timeout) ->
{
link: (scope, element, attrs) ->
attrs.$observe 'gsautofocus', (value) ->
console.log 'value=', value
if value == true
$timeout ->
element[0].focus()
return
return
}
我正在尝试根据控制器变量聚焦输入。它在控制台中正确初始化打印 value= false 并且控制器在视图中而不是在指令中更新变量。我正在使用 jade/coffeescript 或我创建了一个示例,但仅此而已:
控制器
$scope.autofocus = false
$scope.somefunction = ->
$scope.autofocus = true
指令。
'use strict'
angular.module('myapp')
.directive 'gsautofocus', ($timeout, $parse) ->
{
link: (scope, element, attrs) ->
model = $parse(attrs.gsautofocus)
scope.$watch model, (value) ->
console.log 'value=', value
if value == true
$timeout ->
element[0].focus()
return
return
}
查看
input(type="text", gsautofocus="{{autofocus}}")
您应该在属性上使用 $observe
,就像您想要评估每个摘要中的插值包含一样,$watch
不适用于插值。
$观察
$observe(key, fn);
Observes an interpolated attribute. The observer function will be invoked once during the next $digest following compilation. The observer is then invoked whenever the interpolated value changes.
代码
'use strict'
angular.module('myapp')
.directive 'gsautofocus', ($timeout) ->
{
link: (scope, element, attrs) ->
attrs.$observe 'gsautofocus', (value) ->
console.log 'value=', value
if value == true
$timeout ->
element[0].focus()
return
return
}