简体   繁体   中英

AngularJS update ng-init on change

Is there a way in which ng-init will get updated when tableCells will change ? I want to use this approach (or similar) so angular won't have to call findCellsByDate two times.

I also tried to change ng-init with ng-bind or ng-model, but bind will show [object Object] and model will throw an error as there isn't an attribution.

<span ng-init='cells = findCellsByDate(tableCells, day)'>
    <div class='text' ng-show='forecastAndActualForCellsAreNotEmpty(cells)'>
        <span ng-bind='getTotalHoursPercentageForCells(cells)'></span>
        <span>%</span>
    </div>
</span>

I don't think ng-init works that way, so what I'm thinking is that you should change some of your controller/model code to hold a boolean for forecastAndActualForCellsAreNotEmpty which would get updated.

On the other hand you could do it by css. I assume that if forecastAndActualForCellsAreNotEmpty returns false , getTotalHoursPercentageForCells would return 0. So you could bind that to a data attribute and using a css rule make the div go away. But in order to not use ng-init you would have to take the content also with css. And the only way to do that, that I know of, is with :before and :after . Something like

    <div class='text' data-percentage='{{getTotalHoursPercentageForCells(findCellsByDate(tableCells, day))}}'>
    </div>

And the css

div[data-percentage=0]{
    display: none;
}

div[data-percentage]:before{
    content: attr(data-percentage) "%";
    display: block;
}

Now I wouldn't use :before or :after to display actual application content, but rather things that are related to style. So I suppose the final recommendation would be to alter the model instead.

You can put the logic that changes the cells variable inside a watch function that observe changes in tableCells variable

$scope.$watch('tableCells', function(tableCells) {
    if(!tableCells) return;

    $scope.cells = findCellsByDate(tableCells, $scope.day);        
});

In this way you keep that logic in the controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM