Two way binding Angularjs directives isn't working

前端 未结 3 1902
温柔的废话
温柔的废话 2020-12-30 09:01

I have been trying to figure out the solution but I think i hit a dead end.

So here is my directive

directive         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 09:40

    It's much simpler, so I have removed some extra code you had there.

    Please take a look at the code below or working Plunker:

    
    
        
        
        Document
        
    
        
    
        
        
            
        
    
    
    1. The controller sets the initial value to 'Holla'
    2. The directive receives that value by the my-variable attribute
    3. Using two way data-binding any changes made to scope.myVariable updates the $scope.myVariable of the main controller
    4. After few seconds $scope.myVariable changes to 'Bye Bye'
    5. Take a look at your console.log

    $watch and $apply

    Angular's two-way data binding is the root of all awesome in Angular. However, it's not magic, and there are some situations where you need to give it a nudge in the right direction.

    When you bind a value to an element in Angular using ng-model, ng-repeat, etc., Angular creates a $watch on that value. Then whenever a value on a scope changes, all $watches observing that element are executed, and everything updates.

    Sometimes, usually when you're writing a custom directive, you will have to define your own $watch on a scope value to make the directive react to changes.

    On the flip side, sometimes you change a scope value in some code but the app doesn't react to it. Angular checks for scope variable changes after pieces of your code have finished running; for example, when ng-click calls a function on your scope, Angular will check for changes and react. However, some code is outside of Angular and you'll have to call scope.$apply() yourself to trigger the update. This is most commonly seen in event handlers in custom directives.

提交回复
热议问题